Simple script for monitoring a mailserver

emailmonitoringpostfix

I would like to use a bash script (python would be second best) to monitor regularly (hourly) if my mailserver is online and operating.

I know that there are dedicated solutions for this task (Nagios, …) but I really need something simple that I can use as a cronjob. Only to see the mailserver is alive.

I know how to talk with a mailserver with telnet, ie:

telnet mail.foo.org 25
EHLO example.com
mail from:
rcpt to:
...

but this is interactive. Is it possible to check with a script that the mailserver is communicating? Obviously, I don't want to go the whole way and actually send an email. I just want to test that the mailserver is responding.

Best Answer

You can use nc to test a SMTP mail server like so:

$ nc -w 5 mail.mydom.com 25 << EOF
HELO mail.mydom.com
QUIT
EOF

NOTE: The options -w 5 tell nc to wait at most 5 seconds. The server to monitor is mail.mydom.com and 25 is the port we're connecting to.

You can also use this form of the above if you find your server is having issues with the HELO:

$ echo "QUIT" | nc -w 5 mail.mydom.com 25

NOTE: This form works well with both Postfix and Sendmail!

Example

Here I'm connecting to my mail server.

$ echo "QUIT" | nc -w 5 mail.bubba.net 25
220 bubba.net ESMTP Sendmail 8.14.3/8.14.3; Sat, 19 Apr 2014 16:31:44 -0400
221 2.0.0 bubba.net closing connection
$

If you check the status returned by this operation:

$ echo $?
0

However if nothing at the other ends accepts our connection:

$ echo QUIT | nc -w5 localhost 25
Ncat: Connection refused.
$

Checking the status returned from this:

$ echo $?
1

Putting it together

Here's my version of a script called mail_chkr.bash.

#!/bin/bash

echo "Checking Mail Server #1"
echo "QUIT" | nc -w 5 mail.bubba.net 25 > /dev/null 2>&1

if [ $? == 0 ]; then
  echo "mail server #1 is UP"
else
  echo "mail server #1 is DOWN"
fi

echo "Checking Mail Server #2"
echo "QUIT" | nc -w 5 localhost 25 > /dev/null 2>&1

if [ $? == 0 ]; then
  echo "mail server #2 is UP"
else
  echo "mail server #2 is DOWN"
fi

Running it:

$ ./mail_chkr.bash 
Checking Mail Server #1
mail server #1 is UP
Checking Mail Server #2
Ncat: Connection refused.
mail server #2 is DOWN
Related Question