Question

I am trying to write a bash script that will from a domain name find it MX records, from them figure out which is the primary (they are not always in order) and then find its IP. (when there are more then one primary MX the first one found would be ok)

For example:

./findmxip.sh gmail.com

Would give me 173.194.71.26. For me to do this I need to host gmail.com then find the primary MX in the results and host it, getting its IP.

Was it helpful?

Solution

To get exactly 0 or 1 answers:

dig +short gmail.com mx | sort -n | nawk '{print $2; exit}' | dig +short -f -

You'll need a non-ancient dig that supports +short.

As noted there may be more than one "primary" MX as the preferences need not be unique. If you want all the IP addresses of all of the lowest preference records then:

dig +short oracle.com mx | sort -n | 
  nawk -v pref=65536 '($1<=pref) {pref=$1; print $2}' | 
  dig +short -f - | uniq

This does not handle the case where there is no MX record and the A record accepts email, an uncommon but perfectly valid configuration.

Sadly all the dig versions I've tested return 0 whether the domain exists or not (NXDOMAIN), and whether any MX records exist or not. You can catch a DNS time-out (rc=9) though. The related host command does return a non-zero rc with NXDOMAIN, but its behaviour is a little inconsistent, it's messy to script and the output harder to parse.

A poor man's error-checking version (inspired by tripleee's comment) that might be slightly more robust depending on your host command is:

DOMAIN=gmail.com
if ! host -t any $DOMAIN >/dev/null 2>&1 ; then
  echo "no such domain"
elif ! host -t mx $DOMAIN >/dev/null 2>&1;  then
  echo "no MX records"
else
  dig +short $DOMAIN mx | sort -n | nawk '{print $2; exit}' | dig +short -f -
fi

(Perversely, you may require an older version of host (bind-8.x) for the -t mx test to work, newer versions just return 0 instead.)

This is just about the point people start backing away nervously asking why you're not using perl/python/$MFTL.

If you really need to write a robust version in bash, check out the djbdns CLI tools and debugging tools which are rather easier to parse (though sadly don't set user exit codes either).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top