Mar 12

This is a simple bash script that establish a reverse SSH tunnel. It also re-establish the tunnel if for some reason is torn down.

The idea is to run the script as a cron-job periodically, say once every five minutes. The script will then check if the tunnel is up and if not, re-establish the tunnel.

This is very handy if you for some reason need to gain access to a remote linux server which is behind a NAT that you don’t control. It also means that you don’t need to care about dynamic DNS’s and such if the remote network changes IP frequently.

#!/bin/sh

# $REMOTE_HOST is the name of the remote system
REMOTE_HOST=my.home.system

# $REMOTE_PORT is the remote port number that will be used to tunnel
# back to this system
REMOTE_PORT=5000

# $COMMAND is the command used to create the reverse ssh tunnel
COMMAND="ssh -q -N -R $REMOTE_PORT:localhost:22 $REMOTE_HOST"

# Is the tunnel up? Perform two tests:

# 1. Check for relevant process ($COMMAND)
pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND

# 2. Test tunnel by looking at "netstat" output on $REMOTE_HOST
ssh $REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_PORT.*LISTEN" \
   > /dev/null 2>&1

if [ $? -ne 0 ] ; then
   pkill -f -x "$COMMAND"
   $COMMAND
fi

Once the tunnel is established it’s easy to connect back to the remote server by simply establishing a SSH connection against the “Remote Port” specified in the script. e.g. ssh -p 5000 localhost

The bash script was originally found on the following site: http://www.brandonhutchinson.com/ssh_tunnelling.html

Comments Off

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.