Keep Alive SSH Sessions

Last Updated on July 19, 2024

To keep an SSH connection alive, you can modify your SSH configuration to send periodic keepalive messages. Here are a few methods to achieve this:

Method 1: Modify the SSH Client Configuration

  1. Edit the SSH client configuration file (/etc/ssh/ssh_config or ~/.ssh/config):
    nano ~/.ssh/config
  2. Add the following lines to send keepalive messages every 60 seconds:
    Host *
        ServerAliveInterval 60
        ServerAliveCountMax 3
    • ServerAliveInterval specifies the interval in seconds between keepalive messages.
    • ServerAliveCountMax specifies the number of keepalive messages that can be sent without receiving a response from the server before the connection is terminated.

Method 2: Modify the SSH Server Configuration

  1. Edit the SSH server configuration file (/etc/ssh/sshd_config):
    sudo nano /etc/ssh/sshd_config
  2. Add or modify the following lines to keep the server alive:
    ClientAliveInterval 60
    ClientAliveCountMax 3
    • ClientAliveInterval specifies the interval in seconds that the server will wait before sending a null packet to the client to keep the connection alive.
    • ClientAliveCountMax specifies the number of client alive messages which may be sent without receiving any messages back from the client.
  3. Restart the SSH service to apply the changes:
    sudo systemctl restart sshd