Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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