Keep SSH Sessions From Disconnecting

With the installation of new firewalls at work I’ve been getting disconnected a lot from hosts I SSH to, due to changes in the inactivity timeouts. It’s particularly inconvenient when I’m tailing a log that hasn’t changed in a while… and then the connection dies, and I don’t notice. Oops. It also happens in various other situations, like NAT through a home router, too. Let the connection sit for a while and you’ll have to recreate it.

I could ask our network guys to change the timeouts, but it turns out there’s a better fix from the client side. SSH protocol version 2 supports server keepalive, essentially NOOPs sent to the server to keep the connection up. You can do it from the command line:

ssh -o ServerAliveInterval=120 hostname.yourcompany.com

and you could alias ssh to “ssh -o ServerAliveInterval=120″ in .bashrc. Better yet, you could also put it in ~/.ssh/config so it always takes effect:

Host *
ServerAliveInterval 120

If you don’t already have a ~/.ssh/config file make sure to chmod it to 600 so it doesn’t complain about permissions. The Host part of this configuration can also be set to a specific host, or a specific pattern (look in the ssh_config man page, way at the end under PATTERNS), if you have varying needs.

Last, you could always stick it in the main client config file, usually /etc/ssh/ssh_config:

ServerAliveInterval 120

In these examples 120 is the number of seconds between keepalives. Adjust accordingly. There is also the ServerAliveCountMax, which governs how many times it’ll try keeping the session alive before it closes it. By default it’s three, so if your remote host doesn’t respond in three intervals it’ll close the connection.

Many graphical SSH clients, like SecureCRT or PuTTY, also have options for sending null packets, NOOPs, or keepalive, just look in their options.

Share this:

Related

Additionally, I would strongly suggest the use of a terminal multiplexer (tmux or screen). This will prevent any annoyances due to potential disconnects while having long jobs running. You just reconnect to both ssh and the tm-session and all is like you left it, jobs keep running etc.