13

I have a small script that checks a large list of domains for their MX records, everything works fine but when the script finds a domain with no record, it takes quite a long time to skip to the next one.

I have tried adding:

query.lifetime = 1.0
or
query.timeout = 1.0

but this doesn't seem to do anything. Does anyone know how this setting is configured?

My script is below, thanks for your time.

import dns.resolver
from dns.exception import DNSException
import dns.query
import csv

domains = csv.reader(open('domains.csv', 'rU'))
output = open('output.txt', 'w')
for row in domains:
    try:
        domain = row[0]
        query = dns.resolver.query(domain,'MX')
        query.lifetime = 1.0
    except DNSException:
        print "nothing here"
    for rdata in query:
            print domain, " ", rdata.exchange, 'has preference', rdata.preference
            output.writelines(domain)
            output.writelines(",")
            output.writelines(rdata.exchange.to_text())
            output.writelines("\n")
Christopher Long
  • 854
  • 4
  • 11
  • 21

1 Answers1

28

You're setting the timeout after you've already performed the query. So that's not gonna do anything!

What you want to do instead is create a Resolver object, set its timeout, and then call its query() method. dns.resolver.query() is just a convenience function that instantiates a default Resolver object and invokes its query() method, so you need to do that manually if you don't want a default Resolver.

resolver = dns.resolver.Resolver()
resolver.timeout = 1
resolver.lifetime = 1

Then use this in your loop:

try:
    domain = row[0]
    query = resolver.resolve(domain,'MX')
except:
    # etc.

You should be able to use the same Resolver object for all queries.

thinwybk
  • 4,193
  • 2
  • 40
  • 76
kindall
  • 178,883
  • 35
  • 278
  • 309
  • 1
    Yeah, I'm not really sure what the difference is (never used that library) but I'm glad you found the right attribute. – kindall Jan 24 '12 at 17:43
  • Note that `timeout` is only half of the equation. As in OP's original example, `lifetime` should be used too. See http://comments.gmane.org/gmane.comp.python.dnspython.user/144 – James S Apr 26 '14 at 19:11
  • @JameS : link dead. [official doc|http://www.dnspython.org/docs/1.14.0/dns.resolver.Resolver-class.html] "If the lifetime expires, a Timeout exception will occur." . I tested and yes .lifetime was enough to cancel search exception to catch : `dns.exception.Timeout` – Boop Oct 23 '18 at 12:13
  • 1
    [official doc](http://www.dnspython.org/docs/1.14.0/dns.resolver.Resolver-class.html). Meh, my link was ugly. After 5mins can't edit sorry for spam. – Boop Oct 23 '18 at 12:20
  • Brilliant! I had a hard time searching for this answer, but this is the answer!! :) – MaxSteel Sep 19 '19 at 14:17
  • `query = resolver.query(domain,'MX')` should be `query = resolver.resolve(domain,'MX')` nowadays. – thinwybk Jul 14 '22 at 12:38