Skip to content

Instantly share code, notes, and snippets.

@tangnotes
Last active July 4, 2017 16:21
Show Gist options
  • Save tangnotes/2a468cec17616dba12f3f89cc63eba34 to your computer and use it in GitHub Desktop.
Save tangnotes/2a468cec17616dba12f3f89cc63eba34 to your computer and use it in GitHub Desktop.
SSH Port Forwarding
#!/bin/bash
HOSTNAME=YOUR_HOST_NAME
USERNAME=YOUR_USER_NAME
if [ $# -lt 1 ]
then
echo "Usage: $0 PORT [TARGET_PORT]"
exit 1
fi
port=$1
target_port=$2
if [ "x$target_port" == "x" ]
then
target_port=$port
fi
m=$port:localhost:$target_port
_pid=""
function getPid() {
_pid=`ps -o pid,command -e | grep "$m" | grep -v grep | awk '{print $1}'`
}
getPid
if [ "x$_pid" != "x" ]
then
echo "Kill existing process: $_pid..."
kill $_pid
if [ $? -ne 0 ]
then
echo "Error: failed to kill $_pid"
exit 1
fi
fi
ssh -L$m $USERNAME@$HOSTNAME -f -N
if [ $? -ne 0 ]
then
echo "Error: failed to start port forwarding $port"
exit 2
fi
sleep 3
_pid=""
getPid
if [ "x$_pid" == "x" ]
then
echo "Error: failed to start port forwarding $port(2)"
exit 3
fi
echo "Started, pid: $_pid"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment