python -- DNS處理模塊dnspython
阿新 • • 發佈:2018-02-09
size 實例 郵件 arp query resp port 解析結果 一級域名
簡介
dnspython – 是python實現的一個DNS工具包,利用其查詢功能來實現dns的服務監控及解析結果的校驗
安裝dnspython
pip install dnspython
使用
常見的DNS解析類型包括A、MX、NS、CNAME
(1)A記錄的查詢,實例如下:
import dns.resolver domain = raw_input(‘Please input an domain: ‘) A = dns.resolver.query(domain, ‘A‘) for i in A.response.answer: for j in i.items: print j.address
運行輸入:www.baidu.com,輸出結果如下:
(2)MX記錄
domain = raw_input(‘Please input an domain: ‘) MX = dns.resolver.query(domain, ‘MX‘) for i in MX: print ‘MX preference =‘, i.preference, ‘mail exchanger =‘, i.exchange
運行輸入:163.com,輸出結果如下:
(3)NS記錄
print ‘*************NS****************‘ domain = raw_input(‘Please input an domain: ‘) ns = dns.resolver.query(domain, ‘NS‘) for i in ns.response.answer: for j in i.items: print j.to_text()
輸入:baidu.com,輸出結果如下:
註意:只限輸入一級域名,若輸入www.baidu.com是錯誤的
(4)CNAME記錄
print ‘****************CNAME****************‘ domain = raw_input(‘Please input an domain: ‘) cname = dns.resolver.query(domain, ‘CNAME‘) for i in cname.response.answer: for j in i.items: print j.to_text()
輸入:www.baidu.com,輸出結果如下:
一個綜合的例子:
import dns.resolver import httplib iplist = [] # 定義域名IP列表變量 # appdomain = "www.google.com.hk" # 定義業務域名 appdomain = "www.baidu.com" # 定義業務域名 # 域名解析函數,解析成功IP將追加到iplist def get_iplist(domain=""): try: A = dns.resolver.query(domain, ‘A‘) # 解析A記錄類型 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) # 追加到iplist return True def checkip(ip): checkurl = ip + ":80" getcontent = "" httplib.socket.setdefaulttimeout(5) # 定義http連接超時時間(5秒) conn = httplib.HTTPConnection(checkurl) # 創建http連接對象 try: conn.request("GET", "/", headers={"Host": appdomain}) # 發起URL請求,添加host主機頭 r = conn.getresponse() getcontent = r.read(15) # 獲取URL頁面前15個字符,以便做可用性校驗 finally: if getcontent.lower() == "<!doctype html>": # 監控URL頁的內容一般是事先定義好,比如“HTTP200”等 print ip + " [OK]" else: print ip + " [Error]" # 此處可放告警程序,可以是郵件、短信通知 if __name__ == "__main__": if get_iplist(appdomain) and len(iplist) > 0: # 條件:域名解析正確且至少要返回一個IP for ip in iplist: checkip(ip) else: print "dns resolver error."
python -- DNS處理模塊dnspython