Python Get DNS Records (A, AAAA, TXT, CNAME, NS, SOA, MX) For a Domain

Dnspython is a robust DNS toolkit for Python that you can use to make DNS queries, resolve CNAMEs, test nameservers, do zone transfers, perform dynamic updates, and much more than you can imagine.

In this tutorial, I will cover the basic usage for querying certain types of DNS records for a particular domain (or subdomains) – like A, AAAA, TXT, CNAME, NS, SOA and MX – with the Dnspython package. To start using it, first install the library from PyPI:

$ pip install dnspython

Then, the usage to query DNS records is pretty straightforward:

import dns.resolver

# Prints: 142.250.76.46
answers: dns.resolver.Answer = dns.resolver.resolve('youtube.com')
for rdata in answers:
    print(rdata)

# Prints: 2404:6800:4007:814::200e
answers: dns.resolver.Answer = dns.resolver.resolve('youtube.com', 'AAAA')
for rdata in answers:
    print(rdata)

# Prints:
# ns2.google.com.
# ns3.google.com.
# ns4.google.com.
# ns1.google.com.
answers: dns.resolver.Answer = dns.resolver.resolve('youtube.com', 'NS')
for rdata in answers:
    print(rdata)

# Prints: www3.l.google.com.
answers: dns.resolver.Answer = dns.resolver.resolve('accounts.youtube.com', 'CNAME')
for rdata in answers:
    print(rdata)

# Prints: 0 smtp.google.com.
answers: dns.resolver.Answer = dns.resolver.resolve('youtube.com', 'MX')
for rdata in answers:
    print(rdata)

# Prints (something like):
# "v=spf1 include:google.com mx -all"
# "facebook-domain-verification=64jdes7le4h7e7lfpi22rijygx58j1"
# "google-site-verification=QtQWEwHWM8tHiJ4s-jJWzEQrD_fF3luPnpzNDH-Nw-w"
answers: dns.resolver.Answer = dns.resolver.resolve('youtube.com', 'TXT')
for rdata in answers:
    print(rdata)

If the DNS response does not contain any answer for the query/to the question, then the following exception is thrown:

# dns.resolver.resolve('youtube.com', 'PTR')
dns.resolver.NoAnswer: The DNS response does not contain an answer to the question: youtube.com. IN PTR

Additional Links:

  • For other DNS Rdata types, check out the list here.
  • If you want to explore other use cases by source code, check out the module’s Examples page.
  • To completely dive into all the features and API references, check out the documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *