amazon-s3cronssh-tunneldyndns

check and auto re establish reverse ssh tunnel


I'm establishing a reverse tunnel with $ ssh -fN -R 19999:localhost:22 -i aws-mycert.pem ubuntu@my.dyndns.com and need to make sure it stays up & running even past a server reset. How can I check for the connection in a cron script that then re-establishes the connection autiomatically when required?


Solution

  • A simple way of doing this is using Netcat. The command nc -z localhost 19999 will check if there is something in the local port 19999 listening, so you could use: nc -z localhost 19999 || ssh -fN -R 19999:localhost:22 -i aws-mycert.pem ubuntu@my.dyndns.com to recreate the tunnel if needed.

    However, this only checks that the tunnel is up, but it might be stale. The best solution is to use autossh. Just install it in your machine and use:

    autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -fN -R 19999:localhost:22 -i aws-mycert.pem ubuntu@my.dyndns.com

    Then you just need to run this command when the server starts, which depends on your distribution.

    You can find more details on using autossh at https://www.everythingcli.org/ssh-tunnelling-for-fun-and-profit-autossh/.