How to kill all user sessions using shell script in Linux?

System administrator task can be automated in various ways in Linux.

It drastically reduces the human efforts and saves reasonable time which can be utilized for other productive tasks.

shell script is one of the methods to automate regular jobs.

For a scenario, you want to run a weekly job or EOD job to populate some data for reporting purposes.

To do so, you have to kill all ssh sessions that are currently accessing the application on the system before beginning the job.

Please refer the following article which was written in the past to kill a particular user session on Linux.

Below shell script will remove the active sessions of all the users, by taking the tty value of the user sessions and kill them using the pkill command.

$ sudo vi /opt/script/kill-user-sessions.sh

#!/bin/bash
usession=$(w | awk '{if (NR!=1) {print $2 }}' | tail -n +2)
for i in $usession
do
pkill -9 -t $i
done

Set an executable permission to “kill-user-sessions.sh” file.

$ sudo chmod +x /opt/script/kill-user-sessions.sh

Finally, add a cronjob to automate this script which runs daily at 3AM.

$ sudo crontab -e

0 3 * * * /bin/bash /opt/script/kill-user-sessions.sh

If you want to execute the above script occasionally, use the below format.

$ sudo for i in $(w | awk '{if (NR!=1) {print $2 }}' | tail -n +2); do pkill -9 -t $i; done

How to exclude few users on the system

Use the below script, if you want to exclude any of the users in the system.

In this example, “root” and “ansible” users has been taken as reference for exclusion.

$ sudo vi /opt/script/kill-user-sessions-1.sh

#!/bin/bash
usession=$(w | grep -v "root|ansible" | awk '{if (NR!=1) {print $2 }}' | tail -n +2)
for i in $usession
do
pkill -9 -t $i
done

Set an executable permission to “kill-user-sessions-1.sh” file.

$ sudo chmod +x /opt/script/kill-user-sessions-1.sh

Finally, add a cronjob to automate this script which runs daily at 3AM.

$ sudo crontab -e

0 3 * * * /bin/bash /opt/script/kill-user-sessions-1.sh

If you want to execute the above script occasionally, use the below format.

$ sudo for i in $(w | grep -v "root" | awk '{if (NR!=1) {print $2 }}' | tail -n +2); do pkill -9 -t $i; done

Conclusion

This article gives brief about killing all users and excluding few user sessions using shell script.

Please share and support, if you find this article helpful.

About Magesh Maruthamuthu

Love to play with all Linux distribution

View all posts by Magesh Maruthamuthu

3 Comments on “How to kill all user sessions using shell script in Linux?”

Leave a Reply