I need to check mail servers' IP addresses from a list of domains to see if they match a certain IP address. Specifically:
- Build a list of the domains I want to query
- Dig the MX record(s) of each domain
- Dig the A record(s) of the results of the MX record query for the IP address
- If any of the IPs match a specific IP, return a "yes" or "no"
I'm stuck at step 3.
Here's the relevant portion of my script so far
#!/bin/bash
# Bulk DNS Lookup
#
# File name/path of domain list:
domain_list='domains.txt' # One FQDN per line in file.
# File name of output text
output='ns_output.txt'
# Clears previous output
> $output
# IP address of the nameserver used for lookups:
ns_ip='192.168.250.67'
#
# Seconds to wait between lookups:
loop_wait='1' # Is set to 1 second.
for domain in `cat $domain_list` # Start looping through domains
do
echo $domain "Mail servers" >> $output
MX=$(dig @$ns_ip MX $domain +short) #query MX records from domain list and store it as varial $MX
echo $MX >> $output;
echo " " >> $output
echo " " >> $output
sleep $loop_wait # Pause before the next lookup to avoid flooding NS
done;
The problem is I don't know how to turn the output into a variable so that I can run another A record dig.
c****s.com Name Servers
c****s.com. 14400 IN NS ns1.a****l.com. yes
c****s.com Mail servers
10 mail.c*****s.com. 20 mail2.c****s.com.
Is there any way to query the results to return an IP address for each of the servers returned from the MX query?
Edit: I tried everyone's answer and while they all would have worked, I just found Gilles' easiest to implement. Here's my final code:
MX=$(dig @$ns_ip MX $domain +short) #query MX records from domain list and store it as variable $MX
arr=( $MX ) #creates array variable for the MX record answers
for ((i=1; i<${#arr[@]}; i+=2)); #since MX records have multiple answers, for loop goes through each answer
do
echo ${arr[i]} >> $output; #outputs each A record from above MX dig
dig A +short "${arr[i]}" >> $output #queries A record for IP and writes answer
MX_IP=$(dig A +short "${arr[i]}") #sets IP address from the dig to variable MX_IP
if [[ "${arr[i]}" == *"a****d"* ]] #if the mail server host name contains a***d
then
echo "yes - spam filter" >> $output
else
if [[ $MX_IP == $CHECK_IP ]] #if not, check to see if the mail server's IP matches ours.
then
echo "yes - mail server" >> $output
else
echo "no" >> $output
fi
fi
Here's sample output (domains and IPs censored in a fit of paranoia):
a***l.com Mail servers lastmx.a****d.net.
85.x.x.x
209.x.x.x
95.x.x.x yes - spamfilter
....
mail.b***c.com.
72.x.x.x yes - mail server
backup.b***c.com.
50.x.x.x no
mail2.b***c.com.
50.x.x.x no