Dig DNS Records in a Sample Python Program

Domain Name System is the naming system that helps to translate the ip address of the specific servers, computers to the easy to remember domain names. Python has a module named dnspython which helps to get almost all records types.

There are many kinds of records of a domain name which can be found with the use of the python dnspython module. With the use of dns.resolver() that is provided by the dnspython module, it is possible.

Using the dnspython module, you are able to find the record types of domain names. There are many record types such as A, AAAA, NS, MX, TXT, CNAME, SOA and so on. 

Here at LinuxAPT, we shall look into the python program to find dns record types.

1. How to find specific dns record type ?

To find the specific record type like A record, there is a simple python program which you will see below. We are going to write the python program to check the ip address of the domain name. It is done by finding the A record of the domain. Check the python program as shown below for further details:

$ sudo vim A_record.py

Python Program to find the "A record":

import dnspython as dns
import dns.resolver
#To Find and print A record
result = dns.resolver.resolve('linuxapt.com', 'A')
for val in result:
print('A record:', val.to_text())

Now, you will be able to find A record of the domain name (linuxapt.com):

$ python3 A_record.py

2. How to find all record types ?

In case you need to find and print all record types with a single python program, there is a way to do that with the simple python program. You are able to find all record types such as A, AAAA, NS, MX, TXT, CNAME, SOA and so on. You can check the program code below:

$ sudo vim DNS_records.py

Python program to find all records:

import dnspython as dns
import dns.resolver
#To Find and print records
def get_x_record(domain_name, record_type):
result = dns.resolver.resolve(domain_name, record_type)
for val in result:
if record_type=='CNAME':
print(f'{record_type} record: {val.target}')
print(f'{record_type} record: {val.to_text()}')
except Exception as e:
print(f'{record_type} record: {e}')
domain_name = 'linuxapt.com'
records = ['A', 'AAAA', 'TXT', 'MX', 'NS', 'SOA', 'CNAME']
for record in records:
get_x_record(domain_name, record)

This will find almost all record types of a specific domain name:

$ python3 DNS_records.py

[Need help in fixing DNS configuration issues ? We can help you. ]

This article covers how to dig DNS records by using a simple python program with the use of the python module dnspython. In fact, A Python program is useful to find either a single record type at a time or all record types of a domain name. 

The dig lookup runs queries against DNS servers to retrieve DNS records for a specific name (FQDN - fully qualified domain name). It is possible to lookup any DNS record in this manner.

Related Posts