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_configStep 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:
ClientAliveInterval: Sets a timeout interval in seconds. After this period of inactivity, the encrypted SSH server will send a message through the encrypted channel to request a response from the client. Setting this to300means the server checks the client every 5 minutes.ClientAliveCountMax: Sets the number of client alive messages sent by the server without receiving any response from the client. If this threshold is reached, the server disconnects the client. Setting this to0means the server will terminate the connection immediately after the first idle interval (300 seconds/5 minutes) expires without response.
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 -tIf 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 sshYour Ubuntu SSH server is now configured to automatically drop idle connections based on your specified timeout values.