How to keep SSH connection alive?

How can I keep an SSH connection alive without actively using it. When I use it, it works fine, but when I don't use it for a few minutes, it disconnects. As I get an email each time I connect, how can I keep the SSH session alive?

Note: In my .ssh/config file, at the top I have

Host *
ServerAliveInterval 3

but it doesn't seem to work.


Solution 1:

You need to specify amount of the tries and interval of sending a packet to the server. You can put the following lines in your .ssh/config file:

Host examplehost
    Hostname examplehost.com
    ServerAliveInterval 180
    ServerAliveCountMax 2

This will send a packet to the server every 180 seconds (3 minutes) and it will try two times before it closes the connection after getting no response from the client.

Solution 2:

You can also add these arguments in the ssh command, like so...

ssh -o ServerAliveInterval=180 -o ServerAliveCountMax=2 $HOST

Solution 3:

On Linux and Apple Mac OS X operating systems, the ~/.ssh/config file enables you to specify many SSH settings, including those that keep alive an SSH connection. To do this, follow these steps:

  1. Use your preferred text editor to open the ~/.ssh/config file on your local computer. Note: If the .ssh directory or the config file do not exist, create them.

  2. Add the following lines to the config file. The Host value can be any name you want; it is simply a label for the other settings. The Hostname value is the remote host you want to access; replace example.com with your domain name. Replace username with your own Hosting account username:


    Host example
        Hostname example.com
        Port 7822
        User username
        ServerAliveInterval 240
        ServerAliveCountMax 2

With this configuration, the SSH client sends a packet to the server every 240 seconds (4 minutes) to keep the connection alive. If the client does not receive a response after two tries (as specified by the ServerAliveCountMax setting), it closes the connection.

For detailed information about all of the SSH configuration settings available, type man ssh_config at the command line.

  1. Save the changes to the config file.

  2. Connect to your account using SSH. To do this, simply type ssh example where example represents the Host value you specified in step 2.

Monitor the connection. If it still drops, gradually decrease the ServerAliveInterval setting in the config file until the connection is stable.

Check the following url for more details https://www.a2hosting.com/kb/getting-started-guide/accessing-your-account/keeping-ssh-connections-alive