Keeping Linux SSH Session Alive from Disconnecting – Server and Client Side Fixes

SSH is a very common tool for Linux/Unix platforms. One annoying problem when using SSH is that the connection may get disconnected if the SSH connection is idle for some time under common configurations. Users may run an infinite loop like while true; do uptime; sleep 30; done when there is no work to be done in a SSH session. There are better ways as SSH servers and clients already provide such support and we will discuss these methods in this post.

Client side fixes – per user

The pro is that users can configure the ssh client by themselves. The con is that every user will need to do it.

Linux ssh client

Option 1: Add to your ~/.ssh/config

# Client will send "keep alive" messages every 60 seconds 
# for all server hosts
Host *
    ServerAliveInterval 60

Option 2: Add as a command option

$ ssh -o "ServerAliveInterval 60" example.com

PuTTY

In the Connection category for a session, fill 60 in “Sending of null packets to keep session alive”.

Client side fixes – system wide

The above methods can also be applied for all users on the system.

Add to /etc/ssh/ssh_config

# Client will send "keep alive" messages every 60 seconds
ServerAliveInterval 60

Server side fixes – system wide

The SSH server can be configured to send keep alive messages to avoid idle session being got disconnected so that users will not need any special configurations.

Add to /etc/ssh/sshd_config

# Server will send "keep alive" messages every 60 seconds
ClientAliveInterval 60

References:

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

2 comments:

  1. Nice article. One thing:
    # Server will send “keep alive” messages every 60 seconds
    ClientAliveInterval 298

    Value had been forgotten to set to 60.

Leave a Reply

Your email address will not be published. Required fields are marked *