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.

Configuring keep-alive for your specific Ubuntu user account is the safest and most common method.

  1. Open or create your personal SSH configuration file using a text editor:

    nano ~/.ssh/config
  2. Add the following lines to the file to apply the settings to all remote servers you connect to:

    Host *
        ServerAliveInterval 60
        ServerAliveCountMax 3
  3. Save and close the file (in Nano, press Ctrl+O, Enter, then Ctrl+X).

  4. 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.

  1. Open the global SSH configuration file with administrative privileges:

    sudo nano /etc/ssh/ssh_config
  2. Locate the Host * section. If it does not exist, you can add it at the bottom of the file.

  3. Add the following parameters under Host *:

    ServerAliveInterval 60
    ServerAliveCountMax 3
  4. Save 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_ip

Parameter Explanations