Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 87 lines (74 sloc) 2.23 KB
#!/bin/bash
# Imagine traffic is going from left to right:
# --->$1--->$2
# So if you want a remote host to forward to your local machine, do:
# portfwd me@remote:80 8000
# If you want a local host to forward to a remote host, do:
# portfwd 8000 me@remote:8000
# NOTE: you are forwarding from a remote host to your local machine,
# you must edit the remote host's /etc/ssh/sshd_config (or equivalent)
# to have the following:
# Match User ftseng
# GatewayPorts yes
# To check that the remote port forwarding properly works, you can run the following on the remote server:
# netstat -an | grep <the remote port>
# You should see a line that looks like (for example, if the remote port is 8080):
# tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN
# Also, don't forget to open that port up in the firewall. For example, if using `ufw` and with remote port 8080:
# sudo ufw allow 8080
LOCALRE='^[0-9]+$' # just check if looks like a port
REMOTERE='^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-.]+:[0-9]+$'
is_local() {
if [[ $1 =~ $LOCALRE ]]; then
return 0 # true
else
return 1 # false
fi
}
is_remote() {
if [[ $1 =~ $REMOTERE ]]; then
return 0 # true
else
return 1 # false
fi
}
if is_local $1; then
LOCAL=$1
elif is_remote $1; then
REMOTE=$1
fi
if is_local $2; then
LOCAL=$2
elif is_remote $2; then
REMOTE=$2
fi
if [ -z $LOCAL ]; then
echo >&2 "You must specify a local port"
exit 1
elif [ -z $REMOTE ]; then
echo >&2 "You must specify a remote host and port"
exit 1
fi
IFS=':' read -ra ARR <<< "$REMOTE"
REMOTEHOST=${ARR[0]}
REMOTEPORT=${ARR[1]}
LOCALPORT=$LOCAL
if [ "$1" == "$LOCAL" ]; then
function finish {
pkill -f localhost:$LOCAL_PORT
exit 0
}
ssh -N -f -L 0.0.0.0:$LOCALPORT:localhost:$REMOTEPORT $REMOTEHOST
echo "localhost:$LOCAL_PORT is forwarding traffic to ${REMOTEHOST}:${REMOTEPORT} (CTRL+C to stop)"
else
function finish {
pkill -f ${REMOTEPORT}:localhost:${LOCALPORT}
exit 0
}
ssh -f -N -R 0.0.0.0:${REMOTEPORT}:localhost:${LOCALPORT} $REMOTEHOST
echo "${REMOTEHOST}:${REMOTEPORT} is forwarding traffic to ${LOCALPORT} (CTRL+C to stop)"
fi
trap finish INT TERM QUIT EXIT
while true; do
sleep 1
done