Skip to content
shellhacks.dev
Network

Keep an Idle SSH Connection Alive with ServerAliveInterval

Stop idle SSH sessions from dropping with ServerAliveInterval and ServerAliveCountMax. With 30 and 4, a dead peer is detected after about two minutes of silence.

1 min read
Summarize in AI

An SSH session through a firewall or NAT freezes after a few idle minutes, or hangs forever when the network goes away.

Shell
ssh -G example.com | grep -E '^(serveralive|tcpkeepalive)'
cat > cfg <<'EOF'
Host *
  ServerAliveInterval 30
  ServerAliveCountMax 4
EOF
ssh -F cfg -G example.com | grep '^serveralive'
Text
tcpkeepalive yes
serveralivecountmax 3
serveraliveinterval 0
serveralivecountmax 4
serveraliveinterval 30

ssh sends an encrypted probe every ServerAliveInterval seconds when nothing has arrived, and gives up after ServerAliveCountMax probes go unanswered, so the session ends after interval times count seconds, 120 here. The defaults printed by ssh -G are an interval of 0, meaning no probes, and a count of 3. The probes also keep idle NAT entries alive. The options are in ssh_config.

TCPKeepAlive, which is on by default, is a different mechanism: it uses TCP probes that are not encrypted and often wait two hours. Set the alive options on the client for your own connections, or ClientAliveInterval on the server. A shorter interval costs a little traffic and drops sessions on brief outages.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.