Notify me someone is logging into my Linux server

May 13, 2008

If your like me you like to know who is logging into your servers, hopefully this blog entry will help. So the scenerio goes someone has logged into your server through means not legal or ethical at 4 AM and wants to do who knows what. It would be great to get a email notification to your phone and wake up to take care of business. The script below should help:

mkdir /var/log/logins
chown youruser:youruser /var/log/logins

Create the below script and place it some where permissions 755:

#The Below Directory Path is where the script will keep track of logins 
# The two files below checked for a delta against each other 
# Failure Function
echo "Failed: $*"
exit 1
# Function to clean output from the last command
/usr/bin/last | sed '{
 /^reboot /d
/^wtmp begins /d
MYGROUP=`id -gn`
MYIDENT=`id -un`
# Checking the env or error
[ -d ${BASE} ] || mkdir -p ${BASE}
[ -d ${BASE} ] || fail could not create ${BASE}
[ -G ${BASE} ] || fail ${BASE} not owned by ${MYGROUP}
[ -O ${BASE} ] || fail ${BASE} not owned by ${MYIDENT}
# Store current info
clean_last >${CURRENT}
# Is there a history file?
if [ -f ${HISTORY} ]
if ! `cmp --silent $CURRENT $HISTORY`
# Yes mail someone
diff $HISTORY $CURRENT |mail -s "Login report"
# Make current history
[ $? -eq 0 ] || fail mv ${CURRENT} ${HISTORY}
exit 0

Create a crontab for your user to run the script:

*/5 * * * * /path/to/my/script/

This should do it, gives a little more comfort, but I still recommend your typical safe guards IPTABLES, SNORT, etc… best practices.

Comments for “Notify me someone is logging into my Linux server”

  1. Krypton commented on January 10, 2019

    nice job man

    its good but i want to know when the webhosting manager loginto my vps (root) how can i know that

Leave a Reply