Tracking User Login and Logout in your system using shell script

Mahedi Hasan Jisan
2 min readOct 11, 2018

Shell script is a command line interpreter. You can do some pretty amazing stuff using shell script.

In the previous post, I have showed some basic shell script to start with. Link

Let’s start shall we?

First we need who are the current user in the system. you can find out by using: (This program are based on UNIX shell)

echo "The Current Users are:"
echo "$USER"

We are going to check user statistic by every 10 seconds. So of course our program will be running in While True. We are going to take user list before 10 seconds and after 10 seconds.

who | cut -d' ' -f1 | sort -u > user1
sleep 10

who | cut -d' ' -f1 | sort -u > user2

In the above code, who will extract current user information before 10 seconds. Using cut you will be able to cut the user name from the output of who from the position f1. You can sort the name and put those names in a file named user1. After 10 seconds, we use the procedure to retrieve the new user list and store them in user2 file.

Now, we need to check who logs in after 10 second or who log out after 10 seconds.

diff user1 user2 | grep ^\< | cut -d' ' -f2 > login
diff
user1 user2 | grep ^\< | cut -d' ' -f2 > logout

In above code, we find out the difference between two files and cut the user name from position f2 to store then in accordingly in login and logout file.

num=0
if [[ -s login ]]
then
for
i in `cat login`
do
num=1
echo "user ($i) is logged in"
done
fi
if [[ -s
logout ]]
then
for
i in `cat logout`
do
num=1
echo "user ($i) is logged out"
done
fi
if [[
$num == 0 ]]
then
echo "No user has logged in/out in the last 3 seconds."
else
continue
fi

In the above code, we check if any user logs in after 10 seconds, then we will print echo “user ($i) is logged in” or if any user logs out then we will print echo “user ($i) is logged out”. We also track if there is no user logs in or logs out of the system using num variable.

So, that’s pretty much it is. Simple and efficient. I had fun with shell script. I hope you guys will too.

Thanks for reading. if you find any mistake, feel free to point those out. I would appreciate that.

Cheers 😆

--

--