Search code examples
pythonlistpython-2.7dnsresolver

Python Lists - How do I use a list of domains with dns.resolver.query for loop


print (data[1])
ymcacanada.ca

answers = dns.resolver.query(data[1]), 'MX')
traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "dns\resolver.py", line 981, in query
File "dns\resolver.py", line 912, in query
File "dns\resolver.py", line 143, in __init__
dns.resolver.NoAnswer

I expected the data[1] to be equal to "ymcacanada", so I can call the whole data list in a for loop with the dns.resolver looking up the MX records.

What I got was this error that does not happen when I manually run the code with the url.

The next thing I want to do is write those lookups into a .CSV

Here's my code so far(doesn't work!)

import dns
import dns.resolver
import os
import csv
import dns.resolver

file = "domains.txt"
f = open(file)
data = f.read()
f.close
list = []

for url in data:
    answers = dns.resolver.query(url, 'MX')
    for rdata in answers:
        x = [rdata.exchange, rdata.preference]
        print(x)
        list.append([x])

EDIT

Hey All here is my working Code in it's totality. I'm sure it can be improved but I'm still learning!

import dns
import dns.resolver
import os
import csv

##tested on python 2.7 only

errcountA = 0
errcountMX = 0
listoflists = []

with open("domains.txt") as f:
    for url in f:
        A = []
        MX = []
        url = url.strip()
        try: 
            answers = dns.resolver.query(url, 'A') ##Get the A record
            for rdata in answers:
                A.append(rdata.address) ## Add A Records to list
        except: ## Incase the URL doesnt resolve
            A = "Error resolving"
            errcountA += 1

        try: ##Get the MX record
            answers = dns.resolver.query(url, 'MX')
            for rdata in answers:
                MX.append([rdata.preference, rdata.exchange])

        except: ##incase url doesnt resolver
            MX = "Error resolving"
            errcountMX += 1

        list = [url, MX, A]
        print(list)
        listoflists.append(list)

with open('output.csv', 'wb') as csvfile: ##write the csv file
    writer = csv.writer(csvfile)
    for r in listoflists:
        writer.writerow(r)

print listoflists
print ("There were %e A record errors") %errcountA
print ("There were %f MX record errors") %errcountMX
print ("Done!")

Solution

  • Your url data includes the trailing newline. Use .strip() to remove any leading or trailing whitespace from your data. Try this:

    with open("domaints.txt") as f:
        for url in f:
            url = url.strip()
            answers = dns.resolver.query(url, 'MX')
            # Continue as before