Skip to content

Instantly share code, notes, and snippets.

@evan-burke
Last active November 29, 2021 13:00
Show Gist options
  • Save evan-burke/8944e74071531e7dc2cd838cf25067a0 to your computer and use it in GitHub Desktop.
Save evan-burke/8944e74071531e7dc2cd838cf25067a0 to your computer and use it in GitHub Desktop.
quick dnspython usage reference
# https://github.com/rthalley/dnspython
# pip install dnspython
# NOTE reverse DNS lookups on Docker seem to be failing with Docker versions between ~18.6 and ~19.03.8, as of 2020-05-13
# This generates errors like:
# `The DNS response does not contain an answer to the question: 9.8.7.6.in-addr.arpa. IN PTR`
# Workaround: start containers with external DNS where possible using the --dns flag in 'docker run'
import dns.resolver
import sys
def lookup(domain, lookup_type='a', resolver=None):
# resolver is an instance of dns.resolver.Resolver. Use if you need to override default config.
if lookup_type.lower() == 'ptr':
# Convenience functions for reverse lookup handling IP input as ipaddress or string types
if 'ipaddress' in sys.modules and isinstance(domain, ipaddress.IPv4Address):
domain = domain.reverse_pointer
elif isinstance(domain, str) and '.in-addr.arpa' not in domain:
# assume input is an IP and generate the reverse hostname, e.g., 9.8.7.6.in-addr.arpa.
### todo: regex check to make sure input looks like an IP
domain = dns.reversename.from_address(domain)
try:
if resolver is not None:
result = resolver.query(domain, lookup_type)
else:
result = dns.resolver.query(domain, lookup_type)
except dns.exception.DNSException as e:
if isinstance(e, dns.resolver.NXDOMAIN):
result = ['NXDOMAIN']
elif isinstance(e, dns.resolver.NoAnswer):
result = ['NoAnswer']
else:
print("error:", e)
result = []
return [str(i) for i in result]
print(lookup('gmail.com', 'mx'))
# > ['5 gmail-smtp-in.l.google.com.', '30 alt3.gmail-smtp-in.l.google.com.', '20 alt2.gmail-smtp-in.l.google.com.', '40 alt4.gmail-smtp-in.l.google.com.', '10 alt1.gmail-smtp-in.l.google.com.']
# using a custom nameserver other than the default loaded from /etc/resolv.conf:
rslv = dns.resolver.Resolver()
rslv.nameservers = ['1.1.1.1']
# ... lookup('gmail.com', 'mx', resolver=rslv)
# or to point it at an /etc/resolv.conf style file to load config from:
rslv = dns.resolver.Resolver(filename='/path/to/custom/resolv.conf', configure=True)
@djohnnes
Copy link

Hi friends,

I am new to dnspython, I would like to write a script that can delete, add or update old >> to new dns records for my network devices.
anyone has a demo code that I could use eventually?

Thank you,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment