Skip to content

Instantly share code, notes, and snippets.

@grrowl
Created October 22, 2019 00:51
Show Gist options
  • Save grrowl/c653af224b1b070c59a9b48e076e5dce to your computer and use it in GitHub Desktop.
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
#!/bin/bash
if [[ $# -lt 2 ]]
then
echo "Usage: port-forward HOST REMOTE_PORT [LOCAL_PORT]";
else
HOST=$1
REMOTE_PORT=$2
LOCAL_PORT=${3:-${REMOTE_PORT}}
if ! [[ $(lsof -i :$LOCAL_PORT | grep COMMAND) ]]
then
# Port is free, set up tunnel
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
# Call script again with new local port
"$0" "$HOST" "$REMOTE_PORT" $((RANDOM+1000))
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment