If you are logged into a remote Linux system via SSH, you just need to use the exit command to log out of SSH.
That's fine. But what if you want to log out some other user from the SSH connection?
In this quick tip, I'll show you how you can kick any user off the system.
Log out a user from SSH session
First, check the list of logged-in users to your Linux server. There are various ways to do that. I'll use the who command with option
-u. This option displays the process ID of the login shell session of the users.
Here's a sample output:
root@localhost:~# who -u abhishek pts/0 2021-04-05 09:25 00:01 31970 (220.127.116.11) prakash pts/1 2021-04-05 09:26 . 32004 (18.104.22.168) root pts/2 2021-04-05 09:26 . 32039 (22.214.171.124)
Now imagine that I want to kick use
prakash from the SSH session. The process ID of its shell session is 32004. If you kill the login shell session, the user will be disconnected.
To do that, you can use kill command to send a
SIGHUP signal. This signal is used to report that the user’s terminal is disconnected. It also effectively disconnects all processes in the session from the controlling terminal.
sudo kill -HUP 32004
Of course, to perform such an action, you need to be either root or a sudo user.
There are a few things you should know and do.
Send a message before terminating the session
It's a good idea to inform the end user before you terminate his/her session. You can use the write command to quickly drop a message to the user in this manner:
echo "Your session will end in 2 minutes. Save your work!" | write prakash pts/2
Force kill a SSH session if SIGNHUP doesn't work
If the SIGHUP signal does not work, then send SIGKILL signal.
sudo kill -9 32004
You can also log out a user from selected session if the user has more than one SSH session
If the same user is logged in from more than one system or terminal, only the session that you are killing is impacted. It won't kick the user from all the sessions.
This is the case when your SSH session hangs up for some reason like network disconnection. You can kill the terminal and open another SSH session from a new terminal but now you see yourself logged into the system twice.
In such case, you can close the session which should not be active anymore.
You can identify which user to kick off from the timing of the log in which is visible in the output of the
who command. Don't worry, the worst case would be that you kick off yourself from your current session. But then you can log in again.
I hope this quick tip helped you to log out a user from SSH session in Linux. Your questions and suggestions are welcome.