Intro
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.
Idea
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:
- Enable ssh logging from compB to compA without password (there is a lot of howtos: google it)
- Create auto connection script
#!/bin/bash
REMOTEUSER=username
REMOTEHOST=compA #compA IP
SSH_REMOTEPORT=22
SSH_LOCALPORT=19999
COMMAND="$SSH_LOCALPORT:localhost:22 $REMOTEUSER@$REMOTEHOST"
a=`ps -fe | grep "$COMMAND" | grep -v grep`
if [ ! "$a" ]; then
echo "No connection"
ssh -o TCPKeepAlive=yes -fN -R $COMMAND
date >> tunnel.log
else
echo "Connected"
fi
- 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.