Putting this one out there because I spent some time surfing various Well Known Sites and couldn’t find a complete answer.
We had a need to log whenever users logged into a production host – just a notification send to the admins saying someone was on one of the production boxes. The other requirement was to have it be low impact – didn’t need a ton of monitoring packages installed, etc.
The result is a pair of scripts.
The first is ‘checklogin.sh’:
#!/bin/bash
# Nov 6 13:35:25 inf-1 sudo: dshevett : TTY=pts/0 ; PWD=/etc/munin ; USER=root ; COMMAND=/etc/init.d/munin-node restart
TMPFILE=checklogin-$$
AGO=`date "+%b %e %R" -d "1 min ago"`
grep "$AGO" /var/log/auth.log | grep 'session opened for user' | grep -v CRON > /tmp/$TMPFILE
grep "$AGO" /var/log/auth.log | grep 'sudo:'| grep -v pam >> /tmp/$TMPFILE
cat /tmp/$TMPFILE | /tools/sysconf/scripts/mail_if_not_empty ops-notice-internal@REDACTED.com "[inf-1:checklogin.sh]"
rm /tmp/$TMPFILE
This simply looks for some patterns within the auth.log file. The only real trick here is making a date formatted string that is ‘one minute ago’. If this script is run once a minute via a cron job, it’ll send mail within a minute of someone logging into the host.
The other script is a simple utility tool I use for most of my cron jobs called ‘mail_if_not_empty’:
#!/bin/bash
TMPFILE=/tmp/joboutput.$$
TARGET=$1
SUBJECT=$2
cat > $TMPFILE
if [ -s $TMPFILE ]
then
mail -s $SUBJECT $TARGET < $TMPFILE
fi
rm $TMPFILE
Super-duper simple, it just sends mail if there's any output. This makes sure that mail will only be generated if anything interesting happens.