Linux Login Logout Scripts To Send Email
This script / daemon that send email of every login / logout to server. This helps sysadmin aware of login and logout to the server for monitoring purpose. Each line have its comment to understand how it works.
Shell Script
#!/bin/bash
subject=”New login on $(hostname -f)” #variable to set subject of email.email=”test@expertslogin.com” # email address
while true; do #to run as daemon, this will be false everytime.
LASTLOGIN=`last | head -1` # We take last line from output of last command. Last command show last logins/logouts, newest on the top. Head -1 to take first line.
if [ x"$PREVLOGIN" = "x" ]; then # compare if previous value if empty, to avoid sending emails on restart.
PREVLOGIN=$LASTLOGIN # if previous value empty – write to previous value current last line with login.
else # if previous value is not empty – do next:
if [ "$LASTLOGIN" != "$PREVLOGIN" ]; #compare if previous value and last value the same, if not do next:
then
#echo “$LASTLOGIN” | mail -s “$subject” “$email” # uncoment this line if you want to receive emails.First we echo lastlogin line, after redirect it to mail command, mail command to send emails, -s to specify subject, last agrument email to where to sent.echo “$LASTLOGIN $subject” #this line just to write to terminal result.
PREVLOGIN=$LASTLOGIN #if email sent we write to previous value current value, so will sent email only on new entry.
fi # finish of if loop, if previous entry same as last one no need to do anything.
fi # finish of first if loop.
sleep 1 #sleep 1 second, to do nothing, to not use CPU.
done # finish of while loop.
Result
Server:~/$ ./lastlogin.sh
yevhen pts/4 :0.0 Tue Feb 26 15:54 still logged in New login on yevhen.lviv.example.com
yevhen pts/4 :0.0 Tue Feb 26 15:54 – 15:54 (00:00) New login on yevhen.lviv.example.com
yevhen pts/4 :0.0 Tue Feb 26 15:54 still logged in New login on yevhen.lviv.example.com
yevhen pts/4 :0.0 Tue Feb 26 15:54 – 15:54 (00:00) New login on yevhen.lviv.example.com
^C
Since it’s daemon, and while never ends, exited after pressing CTRL+C
Category: LINUX SHELL SCRIPT





