At some point in a Linux System Administrator's career they will need to kick a user off of a system. Usually it is because the user left an open session and you want to reboot the system or do some other maintenance. In this quick tip we will discuss the step's to forcefully kick a user off of a system.

Find a List of Logged In Users

You can use the "who" command to find a list of users currently logged into the system. Using the -u (--users) option will also display the PID (process ID) of the users shell session.

$ who -u
savona pts/1 2019-03-16 09:46 . 6063 (192.168.122.1)
stacy pts/0 2019-03-16 17:07 . 9940 (192.168.122.1)

Let's kick the user "stacy" so we can complete our maintenance.

Warn the User of the Impending Disconnection

It is always best practice to warn users before performing a reboot or disconnection. If the user is doing something malicious or abusing the system in some way, then by all means kick them without warning.

When we ran the who command, it showed us which pts (pseudo terminal) the user is connected to. We can display a message on their terminal by using the echo command and piping it to the write command.

echo "Your session will be terminated in 2 minutes for maintenance." | write stacy pts/0 

You can make the message whatever you like. It is basic etiquette to give the user some time to save their work and log out.

End the Users Shell Process

When you are ready to kick the user, send the SIGHUP to the users shell process. A SIGHUP signal is the same signal the process would receive when the controlling terminal is closed.

sudo kill -HUP 9940

The number at the end of the above command is the process ID of the users shell. We found the process ID using the who command above.

Sometimes there is a process that hangs. In that case we can send a SIGKILL (kill -9) to the PID. This is exactly what it sounds like. It will immediately terminate ANY process, so be careful.

sudo kill -9 9940

My preferred way of kicking a user it to use pkill to send a SIGHUP to all of the users processes. The pkill command is a wrapper for kill and allows for signalling a process by name rather than PID (process ID).

sudo pkill -HUP -u stacy

Disable User Logins

Optionally, you may want to temporarily disable user logins before you start your maintenance.

If you want to learn how to disable user logins read "Disable User Logins to Linux Systems".

Conclusion

You should now know how to disconnect a user from your Linux system. We also discussed some good SysAdmin etiquette. If you have any comments we would love to hear them.