Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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.
#!/bin/sh
# OSX friendly version by jeff donovan
#
# 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=<kenneth.kalmer"
#
if [ -z $1 ]; then
echo "Usage: `basename $0` pattern [/var/log/mail.log]"
echo
exit 1
fi
PATTERN=$1
if [ -z $2 ]; then
MAILLOG=/var/log/mail.log
else
MAILLOG=$2
fi
if [ ! -f $MAILLOG ]; then
echo "Maillog $MAILLOG doesn't exist"
echo
exit 1
fi
touch /var/log/tempfile
TEMPFILE=/var/log/tempfile
egrep "$PATTERN" $MAILLOG | awk '{print $6}' | tr -d : | uniq > $TEMPFILE
for message_id in `cat $TEMPFILE`
do
grep $message_id $MAILLOG
done
rm -f $TEMPFILE
#!/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=<kenneth.kalmer"
#
if [ -z $1 ]; then
echo "Usage: `basename $0` pattern [/var/log/maillog]"
echo
exit 1
fi
PATTERN=$1
if [ -z $2 ]; then
MAILLOG=/var/log/maillog
else
MAILLOG=$2
fi
if [ ! -f $MAILLOG ]; then
echo "Maillog $MAILLOG doesn't exist"
echo
exit 1
fi
TEMPFILE=`tempfile`
egrep "$PATTERN" $MAILLOG | gawk '{print $6}' | tr -d : | uniq > $TEMPFILE
for message_id in `cat $TEMPFILE`
do
grep $message_id $MAILLOG
done
rm -f $TEMPFILE 2>/dev/null
@serenhopy

This comment has been minimized.

Copy link

@serenhopy serenhopy commented Jun 18, 2014

This is very useful, thak you for this awesome script!! I only have a question: In a server that runs postfix + amavis, a message that goes through postfix, amavis and postfix again is interpreted like 3 differents ID's. How could we can edit this script to grep messages which are parsed with amavis only once?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment