-
-
Save grambas/8f983a73f999619cfd7a32789b3c7920 to your computer and use it in GitHub Desktop.
bashrc port forward helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# add these functions in ~/.bashrc | |
# | |
# Easier port forwarding - usage: | |
# | |
# $ portforward 9204 stageX localhost 9200 | |
# | |
# where 'stageX' is an alias from ~/.ssh/config | |
# 9200 is the remote port on localhost | |
# 9204 is local port | |
# | |
function portforward() { | |
if [[ $# -le 1 ]] | |
then | |
echo "Usage: portforward LOCAL_PORT HOST REMOTE_HOST REMOTE_PORT"; | |
return | |
fi | |
LOCAL_PORT=$1 | |
HOST=$2 | |
REMOTE_HOST=$3 | |
REMOTE_PORT=$4 | |
if ! [[ `lsof -i :$LOCAL_PORT | grep COMMAND` ]] | |
then | |
# Port is free - woop! | |
echo "ssh -L $LOCAL_PORT:$REMOTE_HOST:$REMOTE_PORT $HOST -N" | |
ssh -L $LOCAL_PORT:$REMOTE_HOST:$REMOTE_PORT $HOST -N 2> /dev/null | |
[[ $? -ne 0 ]] && echo "Unable to connect to $HOST" | |
else | |
# Recursion ftw | |
portforward $HOST $REMOTE_PORT | |
fi | |
} | |
function _portforward() { | |
# Only autocomplete on the first arg | |
if [[ ${COMP_WORDS[COMP_CWORD-1]} == "portforward" ]] | |
then | |
# Extract host aliases from ~/.ssh/config | |
HOSTS=$(grep --color=never "^Host " ~/.ssh/config | awk '{if ($2 != "*") print $2}') | |
CURRENT_WORD="${COMP_WORDS[COMP_CWORD]}" | |
COMPREPLY=($(compgen -W "$HOSTS" -- $CURRENT_WORD)) | |
return 0 | |
fi | |
} | |
complete -F _portforward portforward |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment