How can I get DNS records for a domain in python?

Question:

How do I get the DNS records for a zone in python? I’m looking for data similar to the output of dig.

Asked By: Dave Forgac

||

Answers:

Try the dnspython library:

You can see some examples here:

Answered By: ars

Your other option is pydns but the last release is as of 2008 so dnspython is probably a better bet (I only mention this in case dnspython doesn’t float your boat).

Answered By: Kurt

A simple example from http://c0deman.wordpress.com/2014/06/17/find-nameservers-of-domain-name-python/ :

import dns.resolver
 
domain = 'google.com'
answers = dns.resolver.resolve(domain,'NS')
for server in answers:
    print(server.target)
Answered By: Willem

You can use python’s socket library to get the DNS records from ip address or domain name

import socket

# if ip address is available
DNS_record = socket.gethostbyaddr("66.249.65.189")

# if domain name is available
DNS_record = socket.gethostbyname("google.com")

For more info on this go to this page https://docs.python.org/2/library/socket.html#:~:text=gethostbyaddr()%20supports%20both%20IPv4%20and%20IPv6.&text=Translate%20a%20socket%20address%20sockaddr,or%20a%20numeric%20port%20number.

Answered By: Augustine Tharakan

dns.resolver.query is deprecated now, it is recommended to use dns.resolver.resolve:

# python3 -m pip install dnspython

import dns.resolver

answers = dns.resolver.resolve("google.com", 'NS')
for server in answers:
    print(server.target)

Answered By: leo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.