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.

<td class="align-left">
  lsof -w -t +d /dev/pts/
</td>
<td class="align-left">
  sort
</td>
<td class="align-left">
  uniq
</td>
<td class="align-left">
  xargs ps -oppid= -p
</td>
<td class="align-left">
  xargs ps -ocomm=,pid=,user= -p
</td>
<td class="align-left">
  awk &#8216;($1 == &#8220;sshd&#8221;) {print $2}&#8217;
</td>
<td class="align-left">
  xargs kill
</td>
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.

ko-fi