Configure SSH Idle Timeout on Ubuntu

This article provides a step-by-step guide on how to configure the OpenSSH server on Ubuntu Linux to automatically disconnect idle sessions after a specific period of inactivity. By modifying the SSH daemon configuration file, you can secure your server against unauthorized access from unattended terminals and free up system resources.

To configure the SSH server to drop idle connections, you will need to modify the SSH daemon configuration file (sshd_config). Follow these steps to set up the idle timeout.

Step 1: Open the SSH Configuration File

Access your Ubuntu server via terminal and open the SSH configuration file using a text editor like nano with administrative privileges:

sudo nano /etc/ssh/sshd_config

Step 2: Configure Client Alive Settings

Scroll through the file to locate the following two directives. If they are commented out (preceded by a #), remove the # symbol. If they do not exist, add them to the bottom of the file:

ClientAliveInterval 300
ClientAliveCountMax 0

How These Settings Work:

For example, if you want a total timeout of 15 minutes, you can set:

ClientAliveInterval 300
ClientAliveCountMax 3

(300 seconds x 3 checks = 900 seconds, or 15 minutes before disconnection).

Step 3: Save and Close the File

If you are using nano, save the changes by pressing Ctrl + O, hit Enter to confirm the filename, and exit the editor by pressing Ctrl + X.

Step 4: Test the SSH Configuration

Before restarting the SSH service, it is best practice to test the configuration syntax for errors to prevent locking yourself out of the server:

sudo sshd -t

If the command returns no output, your configuration is syntactically correct.

Step 5: Restart the SSH Service

Apply the changes by restarting the OpenSSH daemon:

sudo systemctl restart ssh

Your Ubuntu SSH server is now configured to automatically drop idle connections based on your specified timeout values.