piątek, 5 kwietnia 2013

Simple SSH tunnel with auto resuming


There is a lot of tutorials about SSH tunnels. Also there is a number of tutorials about keeping/resuming/checking SSH tunnels. For me all those solutions has a big drawback: either they didn't work when system was rebooted, or they required root privilegs (or both, or simply they didn't work for me).

Here is a simple description how to set up such tunnel with quite smart resuming.


Nothing new here. We want be able to SSH from compA to compB, but compB is behind firewall/NAT, so it is not possible in a normal way (ie ssh compB - red arrow). Thus we have to set up SSH tunnel. Still: nothing new:

On compB:
ssh -R 19999:localhost:22 username@compA

Then on compA we can ssh to compB this way:
ssh localhost -p 19999 -v -l username 
(where 19999 is a port, can be another big number)

But what if SSH connection from compB to compA is lost? We will not be able to connect from compA to compB. Thus, we have to make sure, that this connection (B to A) will be resumed in case of connection lost or system reboot.

How to

On compB:
  1. Enable ssh logging from compB to compA without password (there is a lot of howtos: google it)
  2. Create auto connection script
    REMOTEHOST=compA   #compA IP
    a=`ps -fe | grep "$COMMAND" | grep -v grep`
    if [ ! "$a" ]; then
        echo "No connection"
        ssh -o TCPKeepAlive=yes -fN -R $COMMAND
        date >> tunnel.log
        echo "Connected"
  3. Add it to crontab, eg:
    */5 * * * * ssh_check.sh 1> /dev/null 2> /dev/null
that's it. Now you probably will be able to connect from compA to compB. Even when compB was restarted or connection was lost, as soon as the cron is triggered, the connection will be resumed.

1 komentarz: