Set specific DNS server using dns.resolver (pythondns)

后端 未结 4 1912
孤街浪徒
孤街浪徒 2020-12-03 02:22

I am using dns.resolver from dnspython.

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

相关标签:
4条回答
  • 2020-12-03 03:01

    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:

    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.

    0 讨论(0)
  • 2020-12-03 03:03

    dns.resolver.Resolver.query() is deprecating. Use dns.resolver.Resolver.resolve().See DeprecationWarning at https://github.com/rthalley/dnspython/blob/master/dns/resolver.py

    0 讨论(0)
  • 2020-12-03 03:11

    Yes, it is.

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

    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')
    
    0 讨论(0)
  • 2020-12-03 03:15

    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 nameservers attribute on the Resolver object.

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

    0 讨论(0)
提交回复
热议问题