Prevent closing of SSH Local Port Forwarding

port-forwardingssh-tunnel

I am running various services on an Ubuntu virtual machine running on Azure, and I would like to access some of the services remotely, even though the ports are not open publicly. To do so I have set up a script to do Local Port Forwarding using SSH.

Usually this works by initiaing a connection to the remote host, execute sleep 10 , and establish a connection on the forwarded portbefore the sleep command finishes. This works well when using a service that keeps the connection alive, such as remote SMB shares.

But I have a problem with accessing web services, as the connection closes after some time – from 10-90 seconds after establishing the connection.

To reconnect the connection when it closes I hacked together this little script based on this SO thread.

while true; do { \
    while true; do \
      echo echo ping; sleep 10; \
    done } | ssh -f myapp.cloudapp.net -F .ssh/myapp.cloudapp.net_config  \
             -o ExitOnForwardFailure=yes  sleep 10; echo "$(date) I died"; 
    sleep 1;
done

Unfortunately this "fix" is somewhat flakey, and the connection drops quite often, so the browser hangs on every fifth request. It works, but is far from perfect, so I would like a better approach. Perhaps there could be some kind of script doing long polling or the like? Anyone that has solved this issue?

Best Answer

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.

Related Topic