How to Kill Inactive SSH Sessions

So, you’ve been disconnected from your server a couple of times which resulted in inactive ssh sessions. You know this because when you use the “w” command, you see something like the following…

22:47:28 up 315 days, 21:09, 2 users, load average: 9.04, 8.17, 7.30
root pts/0 ipxxx-xxx-xxx-xxx 23:54 26:40 9.26s 0.86s -bash
root pts/1 ipxxx-xxx-xxx-xxx 22:44 0.00s 0.00s 0.00s w

Using pstree to identify idle SSH sessions

There are a few ways to kill idle ssh sessions. Including editing your sshd_config. But here’s an easy after-the-fact method:

Run this command:

pstree -p

the output will look something like this:

│            └─sshd(16680)───bash(16687)───pstree(17073)

Now look for the parent PID of the session – PID from the line without the “pstree” command. The pstree line, would be you. :)

To kill the idle ssh session, type:

kill 3649

Replace 3649 with your idle ssh session PID. Check afterwards with the “w” command.

Now to prevent this from happening in the future lets edit /etc/ssh/sshd_config and add these two config lines:

ClientAliveInterval 600
ClientAliveCountMax 3

Using htop to identify idle SSH sessions

Another method for identifying idle (orphaned ssh sessions) is by using htop. Notice below the idle ssh session with ‘top’ command left running. I’ll be writing a full article on getting the most out of htop very soon (subscribe to updates). Also see: top, atop, others.

htop pid check

Tags: , ,

How to Kill Inactive SSH Sessions

5 Responses

  1. Excellent, it’s not obvious which PID needed to be axed.

    Adrian August 21, 2016 at 12:48 am #
  2. Thanks, this makes it clearer.

    One note: Both lines that you suggest setting in sshd_config contain the same parameter: “ClientAliveInterval”. I’m guessing one of those is not correct.

    yggdrasil January 3, 2017 at 4:11 pm #
    • Right. Second line should read:
      ClientAliveCountMax 3

      Art Williams March 13, 2017 at 6:03 pm #
    • Yes thanks guys for spotting. Changed to:
      ClientAliveCountMax 3

      Hayden James March 13, 2017 at 6:51 pm #
    • Thanks

      Hayden James March 13, 2017 at 6:50 pm #

Leave a Reply