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:

#!/bin/sh
#
#The Below Directory Path is where the script will keep track of logins 
BASE=/var/log/logins
#
# The two files below checked for a delta against each other 
HISTORY=${BASE}/history
CURRENT=${BASE}/current
#
# Failure Function
fail()
{
echo "Failed: $*"
exit 1
}
#
# Function to clean output from the last command
clean_last()
{
/usr/bin/last | sed '{
 /^reboot /d
/^$/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} ]
then
#
if ! `cmp --silent $CURRENT $HISTORY`
then
# Yes mail someone
#
diff $HISTORY $CURRENT |mail youremail@whatever.com -s "Login report"
fi
fi
#
# Make current history
#
mv ${CURRENT} ${HISTORY}
[ $? -eq 0 ] || fail mv ${CURRENT} ${HISTORY}
exit 0
 
#END OF SCRIPT

Create a crontab for your user to run the script:

*/5 * * * * /path/to/my/script/checklogin.sh

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

Leave a Reply