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’:
# Nov 6 13:35:25 inf-1 sudo: dshevett : TTY=pts/0 ; PWD=/etc/munin ; USER=root ; COMMAND=/etc/init.d/munin-node restart
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]"
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’:
cat > $TMPFILE
if [ -s $TMPFILE ]
mail -s $SUBJECT $TARGET < $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.