Skip to content

Instantly share code, notes, and snippets.

@deadflowers
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save deadflowers/9f1c58e5f907874026dd to your computer and use it in GitHub Desktop.

Select an option

Save deadflowers/9f1c58e5f907874026dd to your computer and use it in GitHub Desktop.
function portforward() {
if [[ $# -ne 2 ]]
then
echo "Usage: portforward HOST PORT";
else
HOST=$1
REMOTE_PORT=$2
# Pick a random port and check it is free
LOCAL_PORT=$((RANDOM+1000))
if ! [[ `lsof -i :$LOCAL_PORT | grep COMMAND` ]]
then
# Port is free - woop!
echo "Forwarding to port $REMOTE_PORT on $HOST from http://localhost:$LOCAL_PORT"
ssh -f -L $LOCAL_PORT:localhost:$REMOTE_PORT $HOST -N 2> /dev/null
else
# Recursion ftw
portforward $HOST $REMOTE_PORT
fi
fi
}
# Used for autocompletion
function _portforward() {
cur="${COMP_WORDS[COMP_CWORD]}"
if [[ ${COMP_WORDS[COMP_CWORD-1]} == "portforward" ]]
then
# the sed call is there to combat people like me who have "grep --color=always" on by default
hosts=$(grep "Host " ~/.ssh/config | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" | grep -v "#" | grep -v "*" | awk '{print $2}')
COMPREPLY=($(compgen -W "${hosts}" -- ${cur}))
else
# otherwise assume on second arg, so autocomplete service name
ports="22 80 2222 3306 5432 8080 11211 55672 15672"
COMPREPLY=($(compgen -W "${ports}" -- ${cur}))
fi
return 0
}
complete -F _portforward portforward
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment