How to keep ssh connection alive

It becomes annoying sometimes if ssh connection gets terminated very soon if no messages sent between the ssh server and client for sometime but there are ways to keep it alive for long or forever from either client or server side.

From the server side

Open and edit the /etc/ssh/sshd_config on the ssh server

ClientAliveInterval 60
ClientAliveCountMax 0

where ClientAliveInterval can be set to a value greater than 0, meaning the interval seconds to request client messages from the server and setting to 0 means doing nothing and disabling the requests; and ClientAliveCountMax can be set to a value greater than 0, meaning maximum counts of intervals without receiving client messages and setting to 0 means no maximum count limit and the server does not terminate the connection even without receiving any messages from the client.

For example, below combination will keep the connection alive for at least 60 * 3 = 180 seconds before server terminates the session.

ClientAliveInterval 60
ClientAliveCountMax 3

after the change, restart the sshd service to make it take effect

service sshd restart

From the client side

Create a ~/.ssh/config on the ssh client machine (e.g. laptops)

 ServerAliveInterval 60
 ServerAliveCountMax 0

The meaning of the config options is similar to the ones from the server side, varying in that who is the side that is trying to keep the connection alive.

Alternatively pass the options via command line during connection

ssh -o ServerAliveInterval=60 user@instance-1