Guide

How to keep an SSH tunnel connected and reconnect it automatically

Keepalives stop idle SSH tunnels from being dropped and detect dead ones; they do not reconnect anything. Reconnecting needs a supervisor such as autossh, a systemd unit or a tunnel manager, because ssh exits when its connection is lost.

Short answer

To keep an SSH tunnel connected, set ServerAliveInterval 30 (with the default ServerAliveCountMax 3) so idle connections stay open and dead ones are detected in about 90 seconds. To reconnect automatically, run ssh under a supervisor, because ssh exits when the connection is lost: autossh -M 0, a systemd unit with Restart=always, or a tunnel manager. Use key authentication for unattended reconnects.

The methods here use OpenSSH and standard system tools. Transputty, the Windows SSH tunnel manager this site belongs to, is in development with no public build yet; see the release status.

Why do SSH tunnels drop?

An SSH tunnel lives inside one TCP connection. Anything that breaks that connection ends every forward on it.

Cause What happens Helped by
Idle timeout in a NAT router, firewall or load balancer The device forgets a connection that has carried no data for a while. Later packets are silently discarded Keepalives
Sleep or hibernation The computer stops answering; the server or a device in between gives up Reconnection
Network change (Wi-Fi to wired, new Wi-Fi, VPN up or down, mobile data) The local IP address changes, and the old TCP connection cannot continue Reconnection
Server restart or sshd restart The session ends Reconnection
Packet loss or a brief outage TCP retransmits for a while and then gives up, or keepalives time out first Reconnection

The first cause is preventable. The others are not: the connection is gone and a new one has to be made. That is why the two halves of this page, keepalives and reconnection, are separate tools for separate problems.

Keepalives: what each setting really does

Setting Where Default Semantics
ServerAliveInterval Client (ssh_config, -o) 0 (off) If no data has arrived from the server for this many seconds, ssh sends a request through the encrypted channel and expects a reply
ServerAliveCountMax Client 3 How many of those requests may go unanswered before ssh disconnects and exits
ClientAliveInterval Server (sshd_config) 0 (off) The same check from the server's side: sshd asks the client for a reply after this much silence
ClientAliveCountMax Server 3 Unanswered server checks before sshd drops the client
TCPKeepAlive Both On Whether the operating system's TCP keepalive probes are enabled on the connection

With ServerAliveInterval 30 and the default count of 3, an unresponsive server is detected after roughly 90 seconds. The manual gives the same arithmetic for 15 seconds and 45.

Host bastion.example.com
    ServerAliveInterval 30
    ServerAliveCountMax 3

Three points are often misunderstood:

  • Server-alive messages do two jobs. They generate traffic, which resets idle timers along the path, and they detect a dead connection so ssh exits instead of hanging.
  • TCPKeepAlive is not the same thing. It works at the TCP level, outside the encrypted channel, so the manual notes it can be spoofed, whereas server-alive messages cannot. Its timing comes from the operating system, where the first probe is often sent only after a long idle period, far later than most NAT timeouts. The manual also points out its downside: a temporary route outage can kill a session that would otherwise have survived.
  • ClientAliveInterval protects the server. It lets sshd clean up sessions whose clients vanished, which also frees listening ports held by remote forwards. You can only set it if you administer the server.

A shorter interval detects failure sooner and produces a little more traffic. Values from 15 to 60 seconds suit most networks.

PuTTY has an equivalent of the first setting: "Seconds between keepalives (0 to turn off)" on the Connection panel. It keeps idle sessions alive. PuTTY does not reconnect a lost session.

Reconnecting with autossh

autossh starts ssh, watches it, and starts it again when it exits.

autossh -M 0 -N \
  -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
  -o ExitOnForwardFailure=yes \
  -L 5433:db.internal:5432 deploy@bastion.example.com
  • -M 0 turns off autossh's own monitoring port. In that mode autossh restarts ssh only when the ssh process exits.
  • ServerAliveInterval and ServerAliveCountMax are therefore essential: they are what makes ssh exit when the connection dies quietly.
  • ExitOnForwardFailure=yes makes ssh exit if a forward cannot be set up, for instance because the port is still held, so that autossh tries again instead of supervising a session that forwards nothing.

Two documented behaviors surprise people: autossh does not restart ssh after a normal exit, and if the very first attempt fails within the 30-second "gate time" it gives up unless told otherwise (AUTOSSH_GATETIME=0, which -f sets for you). When restarts fail in quick succession, autossh spaces its attempts further and further apart.

A systemd unit for Linux

On a Linux machine that should hold a tunnel permanently, systemd can be the supervisor, with no extra software:

[Unit]
Description=SSH tunnel to db.internal through bastion.example.com
After=network-online.target
Wants=network-online.target

[Service]
User=tunnel
ExecStart=/usr/bin/ssh -NT \
  -o BatchMode=yes \
  -o ExitOnForwardFailure=yes \
  -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
  -i /home/tunnel/.ssh/id_ed25519 \
  -L 127.0.0.1:5433:db.internal:5432 \
  deploy@bastion.example.com
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Save it as /etc/systemd/system/db-tunnel.service, then run sudo systemctl enable --now db-tunnel. BatchMode=yes makes ssh fail instead of waiting at a prompt nobody will see, so the server's host key must already be in the tunnel user's known_hosts: connect once by hand as that user first. RestartSec=10 is a fixed delay. Recent systemd versions can lengthen the delay progressively with RestartSteps= and RestartMaxDelaySec=; check that your version has them.

A Windows approach

Windows includes the OpenSSH client and has no autossh equivalent built in. A PowerShell loop does the job in a basic way:

$delay = 1
while ($true) {
    $started = Get-Date
    ssh -N -o BatchMode=yes -o ExitOnForwardFailure=yes `
        -o ServerAliveInterval=30 -o ServerAliveCountMax=3 `
        -L 5433:db.internal:5432 deploy@bastion.example.com
    if (((Get-Date) - $started).TotalSeconds -gt 60) { $delay = 1 }
    Start-Sleep -Seconds $delay
    $delay = [Math]::Min($delay * 2, 60)
}

To start it at sign-in, create a Task Scheduler task with an "At log on" trigger that runs powershell.exe -File with the script's path.

The honest caveats:

  • The loop cannot tell a network failure from a rejected login. If the key is removed from the server, it retries forever, at up to one attempt a minute.
  • A key with a passphrase needs the Windows ssh-agent service to hold it. Otherwise every attempt fails at once, because BatchMode disables the passphrase prompt, and the loop keeps retrying. See SSH key authentication.
  • There is no status display. You find out the tunnel is down when your application fails.
  • Between attempts the local port is closed, as described next.

What clients see while the tunnel is down

Two separate things break when an SSH connection is lost:

  1. Connections already running through the tunnel are gone. They were channels inside the dead SSH session and cannot be moved to a new one. A database client sees a dropped connection and must reconnect. No tool can prevent this.
  2. The listener. With ssh, autossh, systemd or a script, the local port is owned by the ssh process. When that exits, the port closes, and applications get an immediate "connection refused" until a new ssh is up. Some applications handle that badly and need to be restarted.

There is also a window where the tunnel looks fine and is not: after the path dies and before the keepalives time out, the port is open and connections to it hang. A shorter ServerAliveInterval shrinks that window.

Passwords, keys and unattended reconnects

A supervisor cannot type. ssh has no option to store a password: it prompts on the terminal or through an SSH_ASKPASS helper, and BatchMode=yes turns password prompts off entirely. Unattended reconnection therefore means key authentication. Tools that feed a stored password to ssh exist, and they keep the password in a script or environment variable, which is worse than a key.

For a tunnel-only key, limit what it can do on the server. An authorized_keys line such as this allows forwarding to one destination and nothing else:

restrict,port-forwarding,permitopen="db.internal:5432" ssh-ed25519 AAAAC3... tunnel@workstation

Servers that require a one-time code on every login cannot be reconnected unattended, by design.

Why back off between attempts?

Retrying instantly in a tight loop is harmful. Repeated connection attempts can trip the server's rate limits (MaxStartups), get your address banned by tools such as fail2ban, fill logs, and, if the failure is a rejected login, lock the account. During a real outage a fast loop achieves nothing except battery and CPU use. Exponential backoff, which doubles the wait after each failure up to a cap and resets it after a stable connection, recovers quickly from short interruptions and stays polite during long ones. A rejected login should stop the retries altogether, since repeating it cannot succeed.

How Transputty handles reconnection

Transputty is in development and has no public build yet. This describes the current internal build for Windows 11, where "Reconnect automatically" is on by default for each connection.

  • Keepalive. "Keepalive (s)" is set per connection, 30 seconds by default, and the connection is treated as dead after 3 missed replies. Setting 0 turns it off. A silently dead connection therefore takes roughly 90 to 120 seconds to detect with the defaults, depending on where in the 30-second cycle the path died.
  • Backoff. Reconnect attempts start 1 second apart and double up to 60 seconds, with jitter, and the delay resets after the connection has been up for 30 seconds. The row shows "Reconnecting" with a countdown, and you can retry immediately or stop.
  • Ports stay bound. Local and SOCKS listeners are kept open while reconnecting, and the rule shows "Port held". Applications do not see "connection refused".
  • New connections wait. A client that connects during a reconnect is held for up to 10 seconds. If the tunnel returns in that time the connection proceeds; otherwise it is closed (a local forward resets the connection, a SOCKS client gets an error reply). Connections that were already open when the tunnel dropped are lost, as with any SSH client.
  • The cost of a held port. While a rule shows "Port held", the port still accepts TCP connections although the tunnel is down. A plain port check such as Test-NetConnection 127.0.0.1 -Port 5433 succeeds, and a client waits up to 10 seconds before its connection is closed, where a closed port would have refused it at once. Health checks should make a real request through the tunnel. In 0.1 the hold is fixed at 10 seconds and cannot be switched off.
  • Passwords. A password you typed is kept in memory while the connection is switched on and reused for reconnects, then wiped on disconnect or after a failed login.
  • One-time codes need you. Keyboard-interactive answers, such as one-time codes, are never kept, so those logins ask again at every reconnect. If nobody answers, the prompt times out after 5 minutes and the connection goes to "Failed" until you retry it. Its local ports stay bound in that state and behave as described above. A login that needs a one-time code therefore cannot recover unattended.
  • Remote rules can need a retry. After a reconnect Transputty asks the server again for each remote forward listener. If the server still holds the port for the dead session, the request is refused, the rule shows "Server refused to listen", and in 0.1 it is not requested again automatically. Retry the rule yourself, or set ClientAliveInterval on the server so dead sessions release their ports sooner.
  • Rejected logins are not retried. A refused password or key, or a changed host key, stops the connection instead of looping, to avoid locking the account.
  • Network loss. When Windows reports no network, the connection shows "Waiting for network", retries pause, ports stay held, and attempts resume when the network returns. A connection you switch off yourself never reconnects.
A real dropped link: the connection shows 'Reconnecting' with a countdown to the next attempt, its rule shows 'Port held', and 'Retry now' skips the wait. The app is connected to local test servers with fictional host names. The 'reconnects today' count includes seeded demo history.
After the connection is back, the Statistics tab shows availability and outages. The 24-hour history in this capture is seeded demo data; only the most recent outage is real.

What has not been verified yet: reconnection after sleep and wake, and the response to network changes, are implemented but have so far been tested only by simulated calls to the engine, not with a real Windows sleep cycle or real network switches. The backoff limits and the 10-second hold are fixed, not settings. If you are diagnosing drops with any client, start with SSH tunnel keeps disconnecting, see the features page for the rest of what the app does, and what an SSH tunnel manager is for how tools of this kind compare.

Common questions

How do I keep an SSH tunnel connected?

Set ServerAliveInterval in your SSH client, for example ServerAliveInterval 30 under the host in ~/.ssh/config or -o ServerAliveInterval=30 on the command line. The client then sends a small encrypted message whenever the connection has been silent for 30 seconds, which keeps NAT devices and firewalls from discarding the idle connection and lets ssh notice when the server has gone.

How do I automatically reconnect an SSH tunnel?

Run ssh under something that restarts it, because ssh itself never reconnects. On Linux and macOS use autossh -M 0 with ServerAliveInterval and ExitOnForwardFailure, or a systemd service with Restart=always. On Windows use a PowerShell loop started by Task Scheduler, or a tunnel manager. Use key authentication so no one has to type a password.

What is the difference between ServerAliveInterval and TCPKeepAlive?

ServerAliveInterval sends messages inside the encrypted SSH connection at an interval you choose, and ssh disconnects after ServerAliveCountMax of them go unanswered. TCPKeepAlive uses the operating system's TCP keepalive probes, which are not encrypted, can be spoofed, and by default start only after a long idle period on many systems. For tunnels, ServerAliveInterval is the useful one.

Does PuTTY reconnect automatically?

No. PuTTY has a keepalive setting, Seconds between keepalives on the Connection panel, which helps an idle session survive NAT and firewall timeouts. When the connection is lost, PuTTY reports it and the session, with its tunnels, is over until you start it again. Automatic restarts need an outside script around plink or a different tool.

What happens to my database client when the SSH tunnel drops?

Its open connections through the tunnel are broken and cannot be resumed; the client has to connect again. With plain ssh the local listening port also disappears until ssh is restarted, so new attempts fail with connection refused. Once the tunnel is back on the same port, a client that retries will connect normally.

Sources and further reading

Transputty keeps SSH tunnels running on Windows

Local, remote and SOCKS5 forwards in one window, automatic reconnection with ports that stay bound, and a clear reason when something fails. In development; no public build yet.