author-pic

JOSEPH CHOW

How to keep your SSH sessions alive

Published: October 06, 2020

As a developer, a lot of my work is remote on a server, especially since COVID-19 has made even more work remote. So I always have several SSH sessions open. A pet peeve of mine is coming back to a terminal, pasting in a command, only to see it unresponsive. Luckily, there is an easy fix.

Client Configuration

The fix is we have to configure the SSH daemon to send packets at specified intervals to keep it alive. So let's go to the SSH config files on your system ** /etc/ssh/sshd_config** or ~/.ssh/config for just the current user. And add the following to the file:

Host *
    ServerAliveInterval 300
    ServerAliveCountMax 2

If you want to enable this configuration for a specific server you are connected to you can add these lines:

Host *josephc.how
    ServerAliveInterval 300
    ServerAliveCountMax 2

This will ensure that the OpenSSH server will keep the connections alive. The way it works is the client will wait idle for the ServerAliveInterval time, which is 300 seconds and, after which it will ping the server expecting a response. If no response comes, then it will keep trying the above process till the ServerAliveCountMax times, which is 600 seconds in all.

Server Configuration

You can also configure this on the server side. Go to the config file for OpenSSH at /etc/ssh/sshd_config, and add these lines:

ClientAliveInterval 300
ClientAliveCountMax 2

Now, with this easy fix, your client or server will be sending null packets every five minutes. A quick fix for a small problem.

If you like it, share it!