Created
October 22, 2019 00:51
-
-
Save grrowl/c653af224b1b070c59a9b48e076e5dce to your computer and use it in GitHub Desktop.
Updated version of - https://gist.github.com/kura/5065819 + https://gist.github.com/codeinthehole/5064150 Forwards a list of known ports from localhost to a host
This file contains hidden or 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
| 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]}" | |
| # COMP_CWORD-1 = portforward, i.e. the name of this function, so autocomplete SSH host | |
| 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="5432 3306 55672 15672 8080" | |
| 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