3 DNS processing module dnspython

Posted by fI_Ux on Fri, 19 Nov 2021 14:11:02 +0100

1.3 DNS processing module dnspython

 dnspython yes python Implementation of a DNS Toolkit, which supports almost all record types, can
 Used for query, transmission and dynamic update ZONE Information and support TSIG(Transaction signature) validation message
 and EDNS0(extend DNS). In terms of system management, we can use its query function to realize DNS clothes
 Service monitoring and verification of analysis results can be replaced nslookup and dig And other tools to easily match the existing
 The integration of the platform is described in detail below

1.3.1 detailed explanation of module domain name resolution method
dnspython module provides a large number of DNS processing methods, and the most commonly used method is domain name query. dnspython provides a DNS resolver class - resolver, which uses its query method to realize the query function of domain names. The query method is defined as follows: query (self, QName, rdtype = 1, rdclass = 1, TCP = flame, source = none, raise_on_no_answer = true, source_port = 0)
qname parameter: the domain name to query
rdtype parameter: used to specify the type of RR resource. The following are commonly used:
– A record: replace the host name with the IP address
– MX record: mail exchange record, which defines the domain name of the mail server
– CNAME record: refers to the alias record, which realizes the mapping between domain names
– NS record: domain name server and authorized sub domain of the marked area
– PTR record: reverse parsing. In contrast to A record, it converts IP into host name
– SOA record: SOA tag, the definition of a starting authorization area
rdclass parameter: used to specify the network type. The optional values are IN, CH and HS. IN is the default and is the most widely used
TCP parameter: used to specify whether the TCP protocol is enabled for query. The default value is false (not enabled)
Source and source_port parameter: as the specified query source address and port, the default values are query device ip address and 0
raise_on_no_answer parameter: used to specify whether to trigger an exception when there is no response to the query. The default value is true

1.3.2 examples of common parsing types
Common DNS resolution types include A,MX, NS, CNAME, etc. Using the dnspython.resolver.query method, you can simply implement these DNS type queries and provide data sources for later functions. For example, to monitor the availability of a domain name using DNS polling service, you need to get the current resolution results.

(1) A record
Implementation of A record query method source code

[root@Mankel ~]# vim simple.py
#!/usr/bin/python3
import dns.resolver
domain = input('Please imput an domain: ')   #Enter domain name address
my_resolver = dns.resolver.Resolver()       
A = my_resolver.resolve(domain, 'A')        #Specify A record as the query type
for i in A.response.answer:           #Get the query response information through the response.answer method
        for j in i.items:        #Facilitate response information
                if j.rdtype == 1: #Add judgment, otherwise attributeerror will appear: 'CNAME' object has no attribute 'address'
                        print(j.address)

Run the code to view the results. Take the domain name www.baidu.com as an example

[root@Mankel ~]  python3 simplel.py
Please imput an domain: www.baidu.com
14.215.177.38
14.215.177.39

(2).MX record
Source code of MX record query method

[root@Mankel ~]# vim simple2.py
#!/usr/bin/python3
import dns.resolver
domain = input('Please input an domain: ')
my_resolver = dns.resolver.Resolver()
MX = my_resolver.resolve(domain,'MX')
for i in MX:
        print('MX preference = ',i.preference,'Mail exchanger = ',i.exchange)

Run the code to view the results. Take the 163.com domain name as an example:

[root@Mankel ~]# python3 simple2.py 
Please input an domain: 163.com
MX preference =  50 Mail exchanger =  163mx00.mxmail.netease.com.
MX preference =  10 Mail exchanger =  163mx02.mxmail.netease.com.
MX preference =  10 Mail exchanger =  163mx03.mxmail.netease.com.
MX preference =  10 Mail exchanger =  163mx01.mxmail.netease.com.

(3) . NS record
Source code of NS record query method

[root@Mankel py]# vim simple3.py
#!/usr/bin/python3
import dns.resolver
domain = input('Please input an domain: ')
my_resolver = dns.resolver.Resolver()
ns = my_resolver.resolve(domain,'NS')
for i in ns.response.answer:
        for j in i.items:
                print(j.to_text())

Only enter and domain names, such as baidu.com. If you enter secondary or multi-level domain names, such as www.baidu.com, it is wrong

[root@Mankel ~]# python3 simple3.py
Please input an domain: baidu.com
ns4.baidu.com.
ns3.baidu.com.
ns2.baidu.com.
dns.baidu.com.
ns7.baidu.com.

(4) CNAME record
Implementation of CNAME record query method source code

[root@Mankel ~]# vim simple4.py
#!/usr/bin/python3
import dns.resolver
domain = input('Please input an domain: ')
my_resolver = dns.resolver.Resolver()
cname = my_resolver.resolve(domain,'CNAME')  #Specifies that the query type is CNAME record
for i in cname.response.answer:             
        for j in i.items:
                print(j.to_text())

Take www.baidu.com as an example (the target domain name after the result returns canme):

[root@Mankel ~]# python3 simple4.py 
Please input an domain: www.baidu.com
www.a.shifen.com.

1.3.3 practice: DNS domain name polling service monitoring
In most DNS resolutions, a domain name corresponds to an IP address, but through DNS polling technology, a domain name corresponds to multiple IPS, so as to achieve the simplest and efficient load balancing. However, the biggest disadvantage of this scheme is that the target host cannot be automatically removed when it is unavailable. Therefore, it is very important to monitor the service availability of the business host. This example realizes automatic monitoring by analyzing the resolution IP of the current domain name and combined with service port detection. When adding or deleting IP in domain name resolution, there is no need to change the monitoring script. The implementation architecture is as follows:

1. Steps
1) Realize the resolution of the domain name and obtain the resolution IP list of all A records of the domain name
2) Probe the IP list at HTTP level

2. Code analysis
In the first step of this example, obtain the record information of service domain name A through dns.resolver.query method, query all IP address lists, and then use the request() method of httplib module to request the monitoring page in GET mode to monitor whether the IP services of all services are normal

#!/usr/bin/python3
import dns.resolver
import os
import http.client

iplist=[]
appdomain="www.baidu.com"

def get_iplist(domain=""):
        try:
                my_resolver = dns.resolver.Resolver()
                A = my_resolver.resolve(domain,'A')
        except Exception as e:
                print("dns resolver error: "+str(e))
                return
        for i in A.response.answer:
                for j in i.items:
                        if j.rdtype == 1:
                                iplist.append(j.address)
        return True

def checkip(ip):
        checkurl=ip+":80"
        getcontent=""
        http.client.socket.setdefaulttimeout(5)
        conn=http.client.HTTPConnection(checkurl)

        try:
                conn.request("GET","/",headers = {"host":appdomain})

                r=conn.getresponse()
                getcontent=str(r.read(15))
                #sec = "b'<!DOCTYPE html>'"
                #print(sec)
                print(getcontent)
                print(type(getcontent))
        finally:
                if getcontent == "b'<!DOCTYPE html>'":
                        print(ip+" [ok]")
                else:
                        print(ip+" [error]")

if __name__ == "__main__":
        if get_iplist(appdomain) and len(iplist)>0:
                for ip in iplist:
                        checkip(ip)
        else:
                print("dns resolver error.")

Topics: Python Network Protocol TCP/IP