Preventing Orphaned SSH Sessions

If you run servers offering SSH connections (you are using SSH right? If not, stop reading this immediately and go and learn about it), you may have noticed annoying sessions showing as active when you know that they aren’t. Some people call them orphaned, disconnected or leftover sessions. Since some Unix installations by default, either don’t clean these orphaned sessions up for us or take too long to do so, follow the instructions below and you can start getting the accurate results of “who” is on your system. With this method we aren’t actually removing or clearing the sessions, we’re stopping them from occurring in the first place. Personally, I prefer to use this method rather than using “kill”, rebooting or shell scripts.

The first thing you need to do is find the sshd.conf file on your system, below are the typical locations on common Unix’s.

Debian /etc/ssh/sshd_config

Fedora/Red Hat /etc/ssh/sshd_config

FreeBSD /etc/ssh/sshd_config

Open the sshd_config file on your system in your preferred text editor, mine is vi, so that’s what I’ll use in the example.

vi /etc/ssh/sshd_config

Add the following text and save the changes (i, pp, ESC, wq).

# Add some checks to kill disconnected SSH sessions
KeepAlive yes
ClientAliveInterval 60
ClientAliveCountMax 5

KeepAlive is used to send packets to keep the connection alive, which is useful for certain situations (firewalls or VPNs). ClientAliveInterval is the time period between client “alive” checks. And finally, ClientAliveCountMax is the maximum number of tries before SSH kills the session.

After you’ve made the changes, SSHD must be restarted.

/etc/init.d/sshd restart

(or the equivalent on your distribution)

Hopefully, you should now be able to run the “who” command and only see sessions who are actually logged in. SSHD has a number of configuration options that most people don’t know exist. As usual, “man sshd” for more information.

SHARE THIS POST