Unix / Linux: Kick User Off SSH

Objective: Kick a user off a Unix or Linux machine.

Before we can kick any user off, we need to get the list of logged in users using either the who or w commands.

$ who
ibrahim  pts/1        2017-10-01 12:35 (10.10.16.50)
john     pts/3        2017-10-01 13:18 (10.10.16.44)

Let’s say that we want to kick the user john from the system, we have to list the processes running under this user based on his terminal – pts/3. To do this, we can use the ps command with the -t option.

$ ps -t pts/3
  PID TTY          TIME CMD
28075 pts/3    00:00:00 bash
28193 pts/3    00:00:00 top

Look for a shell process for this user. In the example above, the shell process is bash with a PID of 28075.

Before kicking a user off, it’s good practice to inform the user that he is about to be kicked off. Let’s inform user john that his ssh login session is going to be terminated in one minute using the write command.

$ echo "Your login session is going to be terminated in 60 seconds , save your work now!" | write john pts/3 && sleep 60

Once the 60 seconds have elapsed, send a SIGHUP signal to the bash process. This is to terminate the process in a graceful manner. When the shell receives a SIGHUP signal, it resends the SIGHUP signal to all jobs started by the shell.

$ sudo kill -HUP 28075

If the SIGHUP signal does not work, then you can use the SIGKILL signal to kill the process.

$ sudo kill -9 28075

If you have multiple processes running under that user and if you would like to terminate all processes running under that user, use the pkill command.

$ sudo pkill -HUP -u john

The above command will send SIGHUP signals to all processes running as user john.

ibrahim = {
interested_in(unix, linux, android, open_source, reverse_engineering);
coding(c, shell, perl, php, python, java, javascript, nodejs, angular, react);
plays_on(xbox, ps4);
linux_desktop_user(true);
}