While I realize I could go back and combine this all in to one script.. this is what I have at the moment...

Script 1 is a shell script that when given a domain for an argument (like google.com), it will perform an nslookup and check to see if the domain has MX records. If the domain has MX records, it will take the one with the lowest priority. If the domain does not have MX records, It will perform an nslookup on the domain and grab it's A record. Using the address, it then calls Script 2 to perform a telnet to port 25 to test if the port is opened or closed.

I wrote this script because I have a list of 200K email addresses and my boss wanted to know how many of them were bad.

*NOTE* Script 2 could be used to check any port as we pass it an IP and PORT

 

To start it all.. my file is in CSV format, the email addresses are in column 13.. the second awk grabs the domain from that email address.

for a in `cat file.csv | awk -F , '{print $13}' | awk -F @ '{print $2}'`; do sh test-mx.sh $a; done > output.txt 

Example Output from "sh test-mx.sh google.com"

"google.com" has mail records!.. I tested the first MX record and the result is: 25 OPEN

 


Script 1 (test-mx.sh)

#!/bin/sh

if [ -z $1 ]; then exit; fi
DOMAIN=$1
MXRECORDS=`nslookup -type=mx $DOMAIN | grep exchanger | wc -l`

if [ $MXRECORDS -gt 0 ]
then
SRV=`nslookup -type=mx $DOMAIN | grep exchanger | awk '{print $5 " " $6}' | sort -n | head -1 | awk '{print $2}'`
TEST=`/usr/bin/python /tank/home/dklein/scripts/test-port.py $SRV 25`
echo '"'$DOMAIN'" has mail records!.. I tested the first MX record and the result is: '$TEST
else
SRV=`nslookup blessinghospital.com | grep Address | tail -1 | awk '{print $2}'`
TEST=`/usr/bin/python /tank/home/dklein/scripts/test-port.py $SRV 25`
echo '"'$DOMAIN'" does NOT have mail records and (probably wont/may not) work... I tested the domains IP and the result is: '$TEST
fi

Script 2 (test-port.py)

#!/usr/bin/python

import socket
import sys

if ( len(sys.argv) != 3 ):
print "Usage: " + sys.argv[0] + " <IP or FQDN> <PORT>"
sys.exit(1)

remote_host = sys.argv[1]
remote_port = sys.argv[2]

for port in [int (remote_port)]:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(60)
try:
sock.connect((remote_host, port))
except Exception,e:
print "%d CLOSED " % port
else:
print "%d OPEN" % port
sock.close()