How to terminate active ssh sessions

Several months ago I have shortly described how to close non-responsive ssh session, which comes handy at times. Today I will describe how to close every active ssh session by inspecting existing pseudoterminals.

The idea is quite simple as it can be described just in several simple steps.

List process IDs using pseudoterminals
lsof -w -t +d /dev/pts/
Sort generated list
sort
Remove duplicated entries
uniq
List parent process IDs
xargs ps -oppid= -p
Extend list by process name and owner
xargs ps -ocomm=,pid=,user= -p
Filter sshd processes
awk '($1 == "sshd") {print $2}'
Terminate filtered processes
xargs kill

Use following command to close every active ssh session.

# lsof -w -t +d /dev/pts/ | sort | uniq | \
  xargs ps -oppid= -p | \
  xargs ps -ocomm=,pid=,user= -p | \
  awk '($1 == "sshd") {print $2}' | \
  xargs kill

Use following command to close every active ssh session owned by specified username.

# lsof -w -t +d /dev/pts/ | sort | uniq | \
  xargs ps -oppid= -p | \
  xargs ps -ocomm=,pid=,user= -p | \
  awk '($1 == "sshd" && $3 == "USERNAME") {print $2}' | \
  xargs kill

It is quite simple solution that can be used to identify and close parent processes based on defined criteria.

Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system. He is also open for new opportunities and challenges.

Gdansk, Poland https://sleeplessbeastie.eu