【问题标题】:Set specific DNS server using dns.resolver (pythondns)使用 dns.resolver (pythondns) 设置特定的 DNS 服务器
【发布时间】:2011-04-23 08:07:39
【问题描述】:

我正在使用来自dnspythondns.resolver

是否可以设置服务器的IP地址用于查询?

【问题讨论】:

  • 您能否添加一个指向提供dns.resolver 的库的链接?另外,那不是在dns.resolver 文档中吗?
  • @WoLpH 在ubunty中有一个包名为python-dnspython

标签: python dns


【解决方案1】:

您没有在问题中指定,但假设您使用的是 the resolver from dnspython.org,文档表明您要在 Resolver 对象上设置 nameservers 属性。

虽然提供 /etc/resolv.conf 样式的文件以传递给 constructor's filename argument 可能更容易。

【讨论】:

  • /etc/resolv.conf 不在 Windows 上使用。
【解决方案2】:

虽然这是一个老话题,但我会加入。我遇到了同样的挑战,我想我会分享解决方案。因此,基本上配置文件将填充您正在使用的 dns.resolver.Resolver 的“名称服务器”实例变量。因此,如果您想强制您的解析器使用特定的名称服务器,您可以直接这样做:

import dns.resolver

my_resolver = dns.resolver.Resolver()

# 8.8.8.8 is Google's public DNS server
my_resolver.nameservers = ['8.8.8.8']

answer = my_resolver.query('google.com')

希望有人觉得它有用。

【讨论】:

  • 您可以传递configure=False 以避免读取/etc/resolv.conf 或Windows 注册表。
  • 你可以checkout他们的git仓库,手动切换分支到python3
  • 如果有人遇到这个答案(就像我一样),dnspython 现在支持 Python 3.x(如果您仍在使用它,还支持 2.x)。
  • 有谁知道如何验证哪个服务器回答了?我在任何方法中都找不到它,也没有在 answer.response.to_text()
  • 2021 年更新答案:stackoverflow.com/a/65788144/1438393
【解决方案3】:

是的。

如果你像这样使用便利功能dns.resolver.query()

import dns.resolver
r = dns.resolver.query('example.org', 'a')

您可以重新初始化默认解析器,例如使用特定的名称服务器(或列表),例如:

import dns.resolver
dns.resolver.default_resolver = dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers = ['8.8.8.8', '2001:4860:4860::8888',
                                             '8.8.4.4', '2001:4860:4860::8844' ]
r = dns.resolver.query('example.org', 'a')

或者您可以为某些查询使用单独的解析器对象:

import dns.resolver
res = dns.resolver.Resolver(configure=False)
res.nameservers = [ '8.8.8.8', '2001:4860:4860::8888',
                    '8.8.4.4', '2001:4860:4860::8844' ]
r = res.query('example.org', 'a')

【讨论】:

    【解决方案4】:

    由于没有关于如何在 2021 年使用 dnspython 执行此操作的示例,我想我会发布一个:

    import dns.resolver
    
    resolver = dns.resolver.Resolver()
    resolver.nameservers = ['8.8.8.8'] # using google DNS
    result = resolver.resolve('google.com', 'NS')
    nameservers = [ns.to_text() for ns in result]
    

    输出:

    ['ns1.google.com.', 'ns3.google.com.', 'ns2.google.com.', 'ns4.google.com.']
    

    【讨论】:

    • AttributeError: 'Resolver' object has no attribute 'resolve' 使用最新版本的dnspython
    • @e-info128:确保您使用的是 dnspython 2.0.0 或更高版本。见the documentation
    • 是的,dnspython==2.1.0 来自 pip3。我使用相同的示例解决了这个问题,但将.resolve() 替换为.query()
    猜你喜欢
    • 1970-01-01
    • 2020-07-10
    • 2016-04-19
    • 1970-01-01
    • 2010-12-28
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多