Monday, April 19, 2010

Grepping an Active Log File and Mailing Matches

Recently, I had a need to be alerted by email each and every time a certain user logged in. After a few false starts, I eventually settled on something like this (sanitized and simplified for this blog):
tail -n0 -f /var/log/secure | grep --line-buffered "user" | while read line; do echo $line | mail -s "Found"; done
We use the standard "tail -f" to follow the /var/log/secure file. The "-n0" option is used so that tail will start 0 lines from the end of the file. We only care about new entries in the file, so we start at the very end of the file, ignoring any existing entries.

Next, we pipe that to grep, looking for the username "user". The "--line-buffered" option is used to force grep to flush each and every line of output (instead of waiting for its default buffer to fill). Per the man page, this option can be a performance penalty, but this is not a concern in this scenario.

Then, we pipe that to a while loop that iterates over each line. For each line of output, we generate an email with a subject of "Found" and include what was found in the body of the email.

This solution works quite nicely and can very easily be extended in the following ways:
  • adding multiple grep criteria
  • modifying format of log entry to be emailed
  • changing final action from email to something else (like adding an IPTables drop rule)

1 comment:

JeffSoh said...

Like swatch in a one liner, for on-the-fly situations...