Configure SSH Keep-Alive in Ubuntu to Prevent Timeout
When working on a remote server via SSH in Ubuntu, inactive sessions often disconnect due to firewalls or server-side timeout settings. This article provides a quick and direct guide on how to configure your Ubuntu SSH client to send automatic keep-alive signals, ensuring your terminal connection remains active and stable during periods of inactivity.
To stop SSH connections from timing out, you need to configure your SSH client to periodically send a “keep-alive” packet to the server. This can be done for a single user, system-wide, or on a per-session basis.
Method 1: Configure Keep-Alive for a Single User (Recommended)
Configuring keep-alive for your specific Ubuntu user account is the safest and most common method.
Open or create your personal SSH configuration file using a text editor:
nano ~/.ssh/configAdd the following lines to the file to apply the settings to all remote servers you connect to:
Host * ServerAliveInterval 60 ServerAliveCountMax 3Save and close the file (in Nano, press
Ctrl+O,Enter, thenCtrl+X).Restrict the permissions on the file to ensure SSH can read it securely:
chmod 600 ~/.ssh/config
Method 2: Configure Keep-Alive System-Wide
If you want these settings to apply to every user account on your Ubuntu machine, modify the global SSH client configuration.
Open the global SSH configuration file with administrative privileges:
sudo nano /etc/ssh/ssh_configLocate the
Host *section. If it does not exist, you can add it at the bottom of the file.Add the following parameters under
Host *:ServerAliveInterval 60 ServerAliveCountMax 3Save and exit the editor.
Method 3: Apply Keep-Alive to a Single SSH Session
If you only want to prevent timeout for a specific temporary session without modifying any configuration files, you can pass the options directly in your SSH command:
ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=3 username@remote_host_ipParameter Explanations
ServerAliveInterval 60: Tells your Ubuntu SSH client to send a null packet to the remote server every 60 seconds of inactivity to keep the connection alive.ServerAliveCountMax 3: Instructs the client to attempt sending keep-alive packets 3 consecutive times without receiving a response before terminating the connection. In this case, if the server is completely unresponsive for 180 seconds (60 seconds x 3), the client will disconnect.