How to Keep 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”.

putty-keep-alive.png

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 298

References:

http://www.howtogeek.com/howto/linux/keep-your-linux-ssh-session-from-disconnecting/
http://superuser.com/questions/699676/how-to-prevent-ssh-from-disconnecting-if-its-been-idle-for-a-while
https://sysadmincasts.com/episodes/39-cli-monday-how-to-keep-your-ssh-sessions-alive
http://brakertech.com/ssh-keeps-disconnecting/

Eric Zhiqiang Ma

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.

Leave a Reply

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