Web page archived as of 2018-05-22. Some links & features might not work.

Checking DNS of hosts with a script

I found that I wanted to (automatically) keep an eye on the DNS entries of the hosts and domains which I administrate and which I work with. Sometimes, DNS entries get screwed, mostly due to human error, sometimes servers fail, too, or a domain is transferred but some DNS is not (e.g. SPF records), or a provider simply forgets to delete the MX of his former client, and more.

Here are the essential parts of a simple Bash script do check DNS of a list of host names and IP addresses, and to compare results with a previous run.

We start with setting up the list which we put in variable $MYLIST. Empty lines will be ignored. The format is hostname DNS_record_type1 [DNS_record_type2] […]. For DNS_record_type any supported DNS record type may be used. For example

#!/bin/bash
 
# list of host names and IP addresses to check: 
MYLIST="
www.example.net a mx txt
schamanek.net mx
128.130.51.100 a
_spf1.example.net txt
_spf2.example.net txt
 
fam.tuwien.ac.at a mx
www.fam.tuwien.ac.at a mx
"

Furthermore, we define where to store the results of the previous run ($LOGFILE) and the current, new run ($LOGFILENEW).

LOGFILE=~/dnscheck.log.old
LOGFILENEW=~/dnscheck.log.new
cp /dev/null $LOGFILENEW                   # creates an empty $LOGFILENEW

Eventually, we do the checks by feeding the list into a while loop which reads every line of $MYLIST and runs host for every DNS_record_type (here variable $MYTYPE). Essentially, this means

echo "$MYLIST" \
| while read MYDOMAIN MYTYPES ; do
 
   # go through list of DNS types to look up
   for MYTYPE in $MYTYPES ; do
      host -t $MYTYPE $MYDOMAIN | sort >>$LOGFILENEW
      sleep 1
   done
done

I found that results are more accurate when a dot is appended to the hostnames. Of course, this does not work for IP addresses, so we include a simple test to see if $MYDOMAIN is a host or an IP address. We also want to ignore empty lines:

echo "$MYLIST" \
| while read MYDOMAIN MYTYPES ; do
   test "/$MYDOMAIN/" = '//' && continue   # ignore empty lines in $MYLIST
 
   # check whether MYDOMAIN is likely an IP address,
   # if it is a domain name we set DOT=. so we can do _host $MYDOMAIN$DOT_
   DOT="" ; test "/${MYDOMAIN//[0-9.]/}/" != '//' && DOT=.
 
   # go through list of DNS types to look up
   for MYTYPE in $MYTYPES ; do
      host -t $MYTYPE $MYDOMAIN$DOT | sort >>$LOGFILENEW
      sleep 1
   done
done

Now, the results are stored in $LOGFILENEW. Let's compare this with the previous run and we are done.

# throw out the differences
diff $LOGFILE $LOGFILENEW
 
# move new over old
mv $LOGFILENEW $LOGFILE

HTH.

 
blog/100602_checking_dns_of_hosts_with_a_script.txt · Last modified: 2010-09-22 19:33 by andreas