· 2 min read

autossh: a Heartbeat for Your Tunnel

A reverse tunnel that died silently every few days, and the autossh command that fixed it.

buddinglinuxtooling

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 0 turns off autossh’s own monitoring port and relies on SSH keepalives instead. It is simpler and needs no extra port.
  • ServerAliveInterval 30 sends a ping every 30 seconds.
  • ServerAliveCountMax 3 makes ssh exit after 3 unanswered pings, about 90 seconds. autossh then notices and starts it again.
  • ExitOnForwardFailure yes makes ssh exit if the tunnel port cannot be opened. Without it you can have a connected session with no tunnel.
  • -N means no remote shell, only forwarding.
  • -R 8080:localhost:22 opens 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. Setting AUTOSSH_GATETIME=0 makes 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.

References#