Brief introduction
dnspython– is a Python-implemented DNS toolkit that uses its query capabilities to implement DNS service monitoring and validation of analytic results
Installing Dnspython
Pip Install Dnspython
Use
Common types of DNS resolution include A, MX, NS, CNAME
(1) A record of the query, examples are as follows:
Import Dns.resolverdomain = raw_input (' Please input A domain: ') A = dns.resolver.query (domain, ' a ') for I in a.response.an Swer: For J in I.items: print j.address
Run input: www.baidu.com, the output is as follows:
(2) MX record
Domain = raw_input (' Please input a domain: ') mx = dns.resolver.query (domain, ' mx ') for I in MX: print ' MX preference = ', I.preference, ' mail exchanger = ', I.exchange
Run input: 163.com, the output is as follows:
(3) NS record
print ' *************ns**************** ' domain = raw_input (' Please input a domain: ') NS = dns.resolver.query (domain, ' NS ') for I in Ns.response.answer: for J in I.items: print J.to_text ()
Input: baidu.com, the output results are as follows:
Note: Only enter the first-level domain name, if the input www.baidu.com is wrong
(4) CNAME record
print ' ****************cname**************** ' domain = raw_input (' Please input a domain: ') CNAME = Dns.resolver.query ( Domain, ' CNAME ') for I in Cname.response.answer: for J in I.items: print J.to_text ()
Input: www.baidu.com, the output results are as follows:
A comprehensive example:
Import Dns.resolverimport httplibiplist = [] # define domain name IP list variable # appdomain = "WWW.GOOGLE.COM.HK" # define Business Domain name appdomain = "Www.baid U.com "# define Business Domain # Domain name resolution function, parse successful IP will append to Iplistdef get_iplist (domain=" "): Try:a = dns.resolver.query (domain, ' A ') # Resolves A record type except Exception, e:print "DNS Resolver error:" + str (e) return for I in A.response.answer: For j in I.items:iplist.append (j.address) # Append to IPList return truedef checkip (IP): checkurl = IP + ": GetContent =" "Httplib.socket.setdefaulttimeout (5) # defines the HTTP connection time-out (5 seconds) conn = Httplib. Httpconnection (checkurl) # Create HTTP Connection object Try:conn.request ("GET", "/", headers={"Host": AppDomain}) # initiate URL request, add h OST Host Header R = Conn.getresponse () getcontent = R.read (15) # Gets the first 15 characters of the URL page to make the availability check finally:if Getcon Tent.lower () = = "<!doctype html>": # The content of the Monitoring URL page is generally defined beforehand, such as "HTTP200" and other print IP + "[OK]" else: Print IP + "[Error]" # Here you can put the alarm program, you canIs the message, SMS notification if __name__ = = "__main__": If Get_iplist (AppDomain) and Len (IPList) > 0: # Condition: the domain name resolves correctly and returns at least one IP for i P in Iplist:checkip (IP) else:print "DNS resolver error."
Python--DNS processing module Dnspython