Skip to content

Instantly share code, notes, and snippets.

@grambas
Forked from codeinthehole/portforward.sh
Last active January 23, 2024 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grambas/8f983a73f999619cfd7a32789b3c7920 to your computer and use it in GitHub Desktop.
Save grambas/8f983a73f999619cfd7a32789b3c7920 to your computer and use it in GitHub Desktop.
bashrc port forward helper
# 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