DnsPython:设置查询超时/生存时间

DnsPython:设置查询超时/生存时间

问题描述:

我有一个小的脚本,用于检查大量的MX记录域列表,一切正常,但是当脚本找到没有记录的域时,跳到下一个域会花费很长时间.

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.

我尝试添加:

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")

您要设置超时时间之后,您已经执行了查询.所以那什么也做不了!

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

您要做的是创建一个Resolver对象,设置超时,然后调用其query()方法. dns.resolver.query()只是一个便捷函数,它实例化默认的Resolver对象并调用其query()方法,因此,如果您不想使用默认的Resolver,则需要手动进行操作.

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.query(domain,'MX')
except:
    # etc.

您应该能够对所有查询使用相同的Resolver对象.

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