Terminate dropped SSH sessions
To solve the immediate problem, that the sudoers file is locked, you can simply delete the lock file. It will usually be `/etc/sudoers.tmp"; check the man page for visudo to verify. If you delete the lock file, you can run visudo again.
To delete all sessions which are still left hanging, first find out the pid of your own current session. Then, if your own pid is 12345, do
ps -ef | grep sshd | grep -v -e grep -e root -e 12345 | awk '{print "sudo kill -9", $2}' | sh
You may want to do it without the final | sh
first just to check the PIDs you're planning on killing.
If you're on Linux, you can instead use
pkill -o -u $USER sshd
to kill your oldest SSH session. Continue doing that until your current session is the only one left.
You might also want to set ServerAliveInterval 15
in your .ssh/config
to send a keepalive message every 15 seconds when no data has been sent. man ssh_config
for more information.
This will kill sessions hanging for 2+ days. It could be put as a cron.
for i in `w|awk '{print $2,$5}'|grep days|cut -d' ' -f1`; do fuser -k /dev/$i; done
This will kill all but your (last active session). Run this from terminal.
for i in `w|tail -n+3|awk '{print $2,$5}'|grep -v 0.00s|cut -d' ' -f1`; do fuser -k /dev/$i; done
If you list processes so that you see their command and arguments (like e.g. ps -f
from procps does), you should see then sshd processes called e.g.:
sshd: user@pts/7
The terminal (pts/7
) is the key part here - if you compare it with your current terminal (tty
), you can see which is your active session. There are of course other ways to do that (like looking at the PID of the currently running shell and locating that one in the process tree), but this is likely the easiest one. You can then use something along these lines:
# current tty name
TTY=$(tty | cut -f3- -d/)
# PIDs of other sshd processes
ps -o pid= -o command= -C sshd \
| grep sshd:.*@ \
| grep -v "@$TTY" \
| sed "s/ sshd.*//"
You can then feed the PIDs to kill with xargs
but always make sure you do not kill the main sshd
process which handles new connections.
On a related note, be advised that quite generally parsing ps
output is error-prone (especially across various systems) due to the variability of its output formats (here mitigated to large extent by the use of -o pid= -o command=
).