Short script for searching mail logs

Today I had to search through dozens of mail logs (syslog) located on several mail relays and find all entries related to a particular user.


  • All servers are managed via a remote tty console,
  • The ksh-script must be copy&pasteable
  • All logs are gzipped
  • I need all entries with the same message number (the ninth field) as the found log entry

This is what I came up with:

function ms
for file in $*

gzcat $file > $temp1
fgrep -i $a $temp1 | cut -d” ” -f9 | sort -u > $temp2
for i in `cat $temp2`
fgrep $i $temp1
echo “\n”

rm $temp1 $temp2

This is an example:

# ms ‘to=<root‘ syslog.0.gz syslog.1.gz

Sep 24 00:05:55 relay-mail-1 sendmail[23518]: [ID 801593] m8O05sfe023518: from=<>, size=6747, class=0, nrcpts=1, msgid=<>, proto=ESMTP, daemon=MTA, relay=[]

Sep 24 00:06:05 relay-mail-1 sendmail[23520]: [ID 801593] m8O05sfe023518: to=<>, delay=00:00:11, xdelay=00:00:10, mailer=esmtp, pri=126747, [], dsn=4.0.0, stat=Deferred: Connection timed out with

Sep 24 00:31:33 relay-mail-1 sendmail[27735]: [ID 801593] m8O05sfe023518: to=<>, delay=00:25:39, xdelay=00:01:00, mailer=esmtp, pri=216747, [], dsn=4.0.0, stat=Deferred: Connection timed out with
. . .

As you can see the pattern to=<root was found in the 2nd and the 3d log entries, however the 1st line is also here because it contains the same message number (or whatever it’s called).

2 thoughts on “Short script for searching mail logs”

Leave a Reply

Your email address will not be published. Required fields are marked *