Ever been mid-command on a remote server only for your terminal to freeze, leaving you with a frustrating “Connection reset by peer” or a dropped session? This usually happens because of a default SSH connection timeout set by either your client, the server, or an intervening firewall.
Fortunately, you can fix this by enabling a simple mechanism called a “KeepAlive.”
The Fix: Configure KeepAlives
KeepAlives are small, encrypted messages sent periodically to ensure the connection remains active, preventing timeouts when your session is idle. You can enable them on the client side (recommended) or the server side.
This can be done in two ways: you can either set this on the server side or on the client side. Let’s check both ways.
Definition
ServerAliveInterval: Number of seconds that the client will wait before sending a null packet to the server (to keep the connection alive).
ClientAliveInterval: Number of seconds that the server will wait before sending a null packet to the client (to keep the connection alive).
On Server Side
On the Server side, update client timeout. Increase Client interval in sshd_config,
vi /etc/ssh/sshd_config
Update following parameters & restart the sshd server, (set for 3600 x 2 = 2 hours)
ClientAliveInterval 3600 ClientAliveCountMax 2
Restart sshd server,
systemctl restart sshd
On the Client side
Openssh client
If you are using openssh as client, then on the client side, increase serveralive interval in the config below,
vi /etc/ssh/ssh_config or vi /root/.ssh/config
Add the below lines under the config & save
HOST * ServerAliveInterval 60 ServerAliveCountMax 2
The above configuration will poke the server every 60 seconds if it’s alive or not. Will retry 2 times.
Putty
If you are using Putty as your client, then we need to set a time interval (60 seconds in example below) in order to keep the session alive. This will keep the session alive by poking it every 60 seconds.
