Prevent closing of SSH Local Port Forwarding

Use autossh. It exists as a package and will handle all this without you writing scripts. Also configure Keepalive and ClientAliveInterval, and ServerAliveInterval in ssh configuration files. Options are similar to ssh, but it handles dropped connection automatically.

E.g. to start a reverse tunnel (and leave it running):

server_behind_fw # autossh -M 20000 -f -N your_public_server -R 1234:localhost:22 -C

and then:

your_public_seerver # ssh -p 1234 localhost

will ssh you to server_behind_fw.


Adding my own answer here, as none actually provided a definitive fix for my situation. But it is basically @sivann's answer modified to my specific situation. So give out an upvote to him if it helps you!

Complete command line

# This forwards all requests to my local 39000 port to port 8080 on the server
LOCAL_PORT=39000
REMOTE_PORT=8080
SERVER=myapp.cloudapp.net
autossh -M20000 -N -L $LOCAL_PORT:$SERVER:$REMOTE_PORT myuser@$SERVER

This has so far proved rock stable compared to the hackey script I had cobbled together above.

Using config file

If you want to keep the config in a file per server it would have looked like this

$HOME/.ssh/config_myapp.cloudapp.net

Host myapp.cloudapp.net
User myuser
LocalForward 127.0.0.1:39000 localhost:8080
ServerAliveInterval 5

Command line using config file

autossh -M 12345 -N -F $HOME/.ssh/config_myapp.cloudapp.net 192.168.10.2


Using the -N command line flag for ssh will keep the connection running without needing to execute any command, with that you won't need the sleep command.

Additionally you should set ClientAliveInterval and ServerAliveInterval as explained in this answer.


Instead of muching about with sleep and ping, tell ssh to send keepalive packets. The option you are looking for is ServerAliveInterval. This tells ssh to send some data every few second so the server (as well as any nat firewalls along the way) knows the connection is still open, and your session wont time out. This should still be coupled with a script that will reconnect automatically if the connection does fail for other reasons.

There is an example of configuring it here: http://embraceubuntu.com/2006/02/03/keeping-ssh-sessions-alive/