Thursday, 18 October 2012

nagios script to watch linux log file

This is an example nagios (nrpe) script that will watch /var/log/secure log file, and respond with exit code 0 (OK) or exit code 2 (critical) if "Invalid user" string is found (GREPSTRING variable, this can be easily changed). Few tricky bits, first is how to compare two timestamps in bash, so I choose to convert hour and minute and use timestamp, i.e. number of hours * 60 gives the number of minutes + actual minute. Then it's just simple sub to calculate time difference in minutes between event and current time. Second trick is how to add current minute to our timestamp, because bash doesn't like to add values that has zero (0), so when current minute is 08 (as an example, same for 09 as well), it throw error: "value too great for base (error token is '08')". Solution is quite simple (if you know it, heh), use 10# before 0X minute, i.e. 10#`date +%M` did the trick. It's pretty flexible script, as you can use it to watch any linux log file that has usual linux format, and you can search (or grep, if you prefer to call it that way) for any string you want. And here's the script:


#GREPSTRING="that what you're searching for"
GREPSTRING="Invalid user"
TIMENOW=$((`date +%H` * 60 + 10#`date +%M`))
DATENOW=`date +%b" "%d`
LASTRUN=`grep "${GREPSTRING}" ${LOGDIR}/${LOGFILE} | grep "${DATENOW}" | tail -1 | cut -d" " -f3`
TIMELASTHOUR=`echo ${LASTRUN} | cut -d":" -f1`
TIMELASTMINUTE=`echo ${LASTRUN} | cut -d":" -f2`


if [ ${TIMEDIFF} -le 1 ]
          echo "CRITICAL: last ${GREPSTRING} occurs in log ${LOGFILE} about ${TIMEDIFF} minutes ago"
          exit 2
          echo "OK: no ${GREPSTRING} in log ${LOGFILE} in last minute"
          exit 0

No comments:

Post a Comment