Postfix – exigrep style log greping

One of the things I love about exim is the exigrep tool which is a multi-line grepping tool designed for the exim log output. Now unfortunately Postfix does not have any tool like this build in.

Although I would like to take credit for this there has already been a script created which comes close by Kenneth Kalmer.

Can be downloaded from https://gist.github.com/kennethkalmer/19021 , There is a copy below as well.

Using this tool you can get some good information out of the postfix log. With a little bit of bashyness for instance you can spit out message id / to / from (very basic but useful) once again I can not take credit for this as my bash scripting can be quiet limited.

_log='/var/log/maillog'; 
_search='@DOMAIN.COM'; 
_outputfile='./DOMAINOUTPUTLOGFILE.log'; 
for _id in $(cat $_log | postfixgrep "$_search" | sed -n 's/.\+: \(.\+\): from=<.\+>.\+/\1/p' | uniq | sort); 
  do echo -en "$_id\t" >> $_outputfile; 
  echo -n $(grep "$_id: from=<" $_log | head -n 1 | sed -n 's/.\+from=<\([^>]\+\)>,.\+/\1/p') >> $_outputfile; echo -en '\t' >> $_outputfile; 
  echo $(grep "$_id: to=<" $_log | head -n 1 | sed -n 's/.\+to=<\([^>]\+\)>,.\+/\1/p') >> $_outputfile; 
done;

The output file will have information like:

651F488052      SOMEUSER@gmail.com               info@DOMAIN.COM
6559F88052      support@SOMEOTHERDOMAIN.COM.AU   info@DOMAIN.COM

Below is the postfixgrep script.

#!/bin/sh

# Grep for a pattern through a Postfix mail log, collect the message ids into a temporary
# file and then grep for all occurrences of the ID's in the maillog.
# This is a very intensive operation since it requires 1+N greps through the entire log file,
# where N is the number of unique ID's returned from the first grep.
#
# Usage sample:
#   ./grep-postfix-message-ids.sh @gmail.com
#   ./grep-posftix-message-ids.sh "from= $MAILLOGTEMPFILE

TEMPFILE=`mktemp`
egrep "$PATTERN" $MAILLOGTEMPFILE | gawk '{print $6}' | tr -d : | uniq > $TEMPFILE
for message_id in `cat $TEMPFILE`
do
        grep $message_id $MAILLOGTEMPFILE
done

rm -f $TEMPFILE 2>/dev/null
rm -f $MAILLOGTEMPFILE 2>/dev/null


Leave a Reply