I have a few idle ssh sessions that I want to kill. This remote server is used by many users, how do I identify the pids of the sessions that I own?

When I run who, I get a list of ssh sessions labeled by username.

$ who
me      pts/0        2020-11-23 18:05 (tmux(id).%0)
me      pts/1        2020-11-06 13:28 (<ip 1>)
someone    pts/2        2020-11-09 09:36 (<ip 2>)
someone    pts/3        2020-11-26 20:26 (<ip 2>)

When I run pstree, the sessions are no longer labeled by username.

$ pstree -p | grep sshd 

           |           |-sshd(4285)---sshd(4308)
           |           |-sshd(5428)---sshd(5450)

Unless you are the root user, you will not be able to do anything to anybody else's processes, so there's no danger in just signalling all sshd processes:

pkill sshd

If you want to explicitly limit this to your own processes:

pkill -U "$USER" sshd

or, if the USER variable isn't used in the shell that you are running, try "$LOGNAME" in place of "$USER", or

pkill -U "$(id -un)" sshd

See also the manual for the pkill command.

Use pgrep instead of pkill if you want to get a list of the process IDs of the matched processes. Use pkill or pgrep with -o to only signal or list the oldest process.

  • 1
    Awesome, thanks. And when I run pkill sshd, will that kill the ssh session I'm currently running the command from? And will that also permanently kill my tmux sessions? – user443888 Nov 27 '20 at 16:53
  • @user443888 It would send the TERM signal to all sshd processes that you own. I'm unsure whether that would kill tmux, but I don't think so. It would be fairly easy to test (on my OpenBSD system, it does not kill tmux and I doubt it would do on Linux). – Kusalananda Nov 27 '20 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.