autossh: a Heartbeat for Your Tunnel
A reverse tunnel that died silently every few days, and the autossh command that fixed it.
What I learned#
I kept a reverse tunnel open to my remote server. Every few days it died silently. SSH still looked fine, but nothing went through, which is exactly the zombie SSH problem.
autossh fixes this by starting ssh for you and restarting it whenever it exits.
autossh -M 0 -N \
-o "ServerAliveInterval 30" \
-o "ServerAliveCountMax 3" \
-o "ExitOnForwardFailure yes" \
-R 8080:localhost:22 user@example.com
What each part does:
-M 0turns off autossh’s own monitoring port and relies on SSH keepalives instead. It is simpler and needs no extra port.ServerAliveInterval 30sends a ping every 30 seconds.ServerAliveCountMax 3makessshexit after 3 unanswered pings, about 90 seconds. autossh then notices and starts it again.ExitOnForwardFailure yesmakessshexit if the tunnel port cannot be opened. Without it you can have a connected session with no tunnel.-Nmeans no remote shell, only forwarding.-R 8080:localhost:22opens port 8080 on the remote host and sends it to port 22 on this machine.
Two details that bit me or are easy to miss:
- With
-M 0, if the very first connection fails quickly, autossh gives up. SettingAUTOSSH_GATETIME=0makes it keep retrying. - Use key-based login. An unattended tunnel cannot type a password.
Why it matters#
Keepalives let the client find out that the connection is dead. Without them, the session can sit there for a long time, believing it is still connected. autossh adds the second half: after the failure is noticed, something brings the tunnel back with no human involved.
A reverse tunnel also opens a path into your machine. Keep the remote port bound to localhost unless you really need it public, and allow only key authentication on the machine behind it.
Still unsure#
This only lives as long as the terminal does. Close it or reboot and the tunnel is gone. Running it as a systemd service is the next step, and that will be the next note.