Saturday, March 12, 2016

Kill an ssh connection from the server side

So you don't like Bob today or maybe you want to test a failed connection.. Whatever your reason you need to kill the ssh connections for his user on your server.

The way to kill any ssh connection to your server is to kill the sshd daemon that is handling it. To get a list of the sshd instances on your machine, you can use ps and grep. To get them for a specific user like Bob, just add the -u option to ps:

ps -u bob | grep sshd
You should get a list of all sshd instances owned by bob:
27424 ?        00:00:00 sshd
27535 ?        00:00:00 sshd
27594 ?        00:00:00 sshd

So, now that we have a list of PIDs, we can easily kick Bob out of the server:

ps -u bob | grep sshd | cut -d ' ' -f 1 | xargs -rt sudo kill -1
We're just taking that list from above, getting the PID out of the first (-f 1) space-delimeted (-d '') column with cut, and using xargs to run kill for each of the PIDs. The -r flag tells xargs not to run if the list was empty and the -t flag prints the command before executing it (if you like to see whats going on).

No comments :