How can I keep my SSH sessions from freezing?

The changes you've made in /etc/ssh/ssh_config and /etc/ssh/sshd_config are correct but will still not have any effect.

To get your configuration working, make these configuration changes on the client:

/etc/ssh/ssh_config

Host *
ServerAliveInterval 100

ServerAliveInterval The client will send a null packet to the server every 100 seconds to keep the connection alive

NULL packet Is sent by the server to the client. The same packet is sent by the client to the server. A TCP NULL packet does not contain any controlling flag like SYN, ACK, FIN etc. because the server does not require a reply from the client. The NULL packet is described here: https://tools.ietf.org/html/rfc6592

Then configuring the sshd part on the server.

/etc/ssh/sshd_config

ClientAliveInterval 60
TCPKeepAlive yes
ClientAliveCountMax 10000

ClientAliveInterval The server will wait 60 seconds before sending a null packet to the client to keep the connection alive

TCPKeepAlive Is there to ensure that certain firewalls don't drop idle connections.

ClientAliveCountMax Server will send alive messages to the client even though it has not received any message back from the client.

Finally restart the ssh server

service ssh restart or service sshd restart depending on what system you are on.


Personal suggestion: use screen on the remote host; it will manage to keep your connection alive for as long as it stays active in a terminal.

Here's what I typically add to /etc/screenrc for quick identification of my screen sessions:

hardstatus alwayslastline
hardstatus string "%{= kG}[ %{G}%H %{g}][ %{=kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B}%Y-%m-%d %{W}%c %{g}]"
defscrollback 8192

EDIT : Hints.

The hardstatus string will show a bottom status line such as this one: Screen session example with three open tabs

The scrollback buffer is also extended to 8192 lines instead of the usual 1000-1500 (depending on the distribution).


If the problem is a hibernated laptop or a less-than-prefect network connection, I'd recommend using mosh which runs over ssh and allows automatic reconnecting.

From the website:

Mosh (mobile shell)

Remote terminal application that allows roaming, supports intermittent connectivity, and provides intelligent local echo and line editing of user keystrokes.

Mosh is a replacement for SSH. It's more robust and responsive, especially over Wi-Fi, cellular, and long-distance links.

Mosh is free software, available for GNU/Linux, BSD, macOS, Solaris, Android, Chrome, and iOS.

In combination with tmux (or the older screen), this allows me to connect via ssh to a server from my laptop and stay connected for days even when changing wifi connections and surviving mobile data drop-outs.

Tags:

Ssh