Several months ago I have shortly described how to close a non-responsive ssh session, which comes in 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 | |
Sort generated list | |
Remove duplicated entries | |
List parent process IDs | |
Extend list by process name and owner | |
Filter sshd processes | |
Terminate filtered processes | |
Use the 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 the following command to close every active ssh session owned by a 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
This solution can be used to identify and close parent processes based on defined criteria.