How does tcp-keepalive work in ssh?

I am trying to code a shell-script that uses a ssh-connection for doing “heartbeats”. I want to terminate the client- and server-side of that connection after a certain timeout (after the connection drops).

What I found so far:

  • TCPKeepAlive yes/no for ssh and sshd
  • ClientAliveCountMax for sshd
  • ClientAliveInterval for sshd
  • ServerAliveCountMax for ssh
  • ServerAliveInterval for ssh

To change “ClientAliveCountMax” I would have to modify the sshd_config on each target machine (this option is disabled by default).

So my question is – can I use “TCPKeepAlive” for my purposes, too (without changing anything else on the source/target machines)?

Target operating system is SLES11 SP2 – but I do not think that is relevant here.

Asked By: Nils


You probably want to use the ServerAlive settings for this. They do not require any configuration on the server, and can be set on the command line if you wish.

ssh -o ServerAliveInterval=5 -o ServerAliveCountMax=1 $HOST

This will send a ssh keepalive message every 5 seconds, and if it comes time to send another keepalive, but a response to the last one wasn’t received, then the connection is terminated.

The critical difference between ServerAliveInterval and TCPKeepAlive is the layer they operate at.

  • TCPKeepAlive operates on the TCP layer. It sends an empty TCP ACK packet. Firewalls can be configured to ignore these packets, so if you go through a firewall that drops idle connections, these may not keep the connection alive.
  • ServerAliveInterval operates on the ssh layer. It will actually send data through ssh, so the TCP packet has encrypted data in and a firewall can’t tell if its a keepalive, or a legitimate packet, so these work better.
Answered By: phemmer

The TCPKeepAlive option is actually a very different method of keeping connections alive from ClientAlive-like or ServerAlive-like options.

Are per BSD SSH manual page, we can read that:

The client alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The client alive mechanism is valuable when the client or server depend on knowing when a connection has become inactive.

The TCPKeepAlive make sure whether the system should send TCP keepalive messages to the other side. The default option is always enabled.

If you’re using ClientAliveInterval, you can disable TCPKeepAlive. This option will send a message through the encrypted channel to request a response from the client (the default is 0, so no messages are sent to the client) and ClientAliveCountMax sets the number of client alive messages before sshd will disconnect the client, by terminating the session.

Answered By: kenorb
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.