Set specific DNS server using dns.resolver (pythondns)

PythonDns

Python Problem Overview


I am using dns.resolver from dnspython.

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

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

Since there's no example of how to do this with dnspython in 2021, I thought I'd post one:

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]

Output:

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

Solution 4 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMassimoView Question on Stackoverflow
Solution 1 - PythonMarcin WyszynskiView Answer on Stackoverflow
Solution 2 - PythonmaxschlepzigView Answer on Stackoverflow
Solution 3 - PythonAmal MuraliView Answer on Stackoverflow
Solution 4 - PythonbstpierreView Answer on Stackoverflow