使用 dns.resolver (pythondns) 设置特定的 DNS 服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3898363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:15:28  来源:igfitidea点击:

Set specific DNS server using dns.resolver (pythondns)

pythondns

提问by Massimo

I am using dns.resolverfrom dnspython.

我正在使用dns.resolver来自dnspython

Is it possible to set the IP address of the server to use for queries ?

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

采纳答案by Marcin Wyszynski

Although this is somewhat of an old thread, I will jump in. I've bumped against the same challenge and I thought I would share the solution. So, basically the config file would populate the 'nameservers' instance variable of the dns.resolver.Resolver you are using. Hence, if you want to coerce your Resolver to use a particular nameserver, you can do it direcly like this:

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

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

Hope someone finds it useful.

希望有人觉得它有用。

回答by bstpierre

You don't specify in your question, but assuming you're using the resolver from dnspython.org, the documentation indicates you want to set the nameserversattribute on the Resolver object.

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

Though it may be easier to provide an /etc/resolv.conf-style file to pass to the constructor's filenameargument.

虽然提供一个 /etc/resolv.conf 样式的文件来传递给构造函数的filename参数可能更容易。

回答by maxschlepzig

Yes, it is.

是的。

If you use the convenience function dns.resolver.query()like this

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

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

you can re-initialize the default resolver such such a specific nameserver (or a list) is used, e.g.:

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

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

Or you can use a separate resolver object just for some queries:

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

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