DNS处理模块dnspython

dnspython模块安装

1 http://www.dnspython.org/kits/1.9.4/dnspython-1.9.4.tar.gz
2 tar -xf dnspython-1.9.4.tar.gz
3 cd dnspython-1.9.4
4 python setup.py install

dnspython模块提供了大量的DNS处理方法,最常用的方法是域名查询。dnspython提供了一个DNS解析器类----resolver,使用它的query方法来实现域名的查询功能

(1)A记录

 1 #!/usr/bin/env python
 2 #coding=utf-8
 3 
 4 import dns.resolver
 5 domain = raw_input('Please input an domain: ')
 6 
 7 A = dns.resolver.query(domain,'A')
 8 
 9 
10 if __name__=="__main__":
11     for i in A:
12         print i.address

(2)MX记录

1 #!/usr/bin/env python
2 #coding=utf-8
3 
4 import dns.resolver
5 domain = raw_input('Please input an domain: ')
6 
7 MX = dns.resolver.query(domain,'MX')
8 for i in MX:
9     print 'MX preference =', i.preference, 'mail exchanger= ', i.exchange

实践:DNS域名轮询业务监控

 1 #!/usr/bin/env python
 2 #coding=utf-8
 3 
 4 import dns.resolver
 5 import os
 6 import httplib
 7 
 8 iplist = []
 9 appdomain = "baidu.watchslowly.com"
10 def get_iplist(domain=""):
11     try:
12         A = dns.resolver.query(domain,'A')
13     except Exception,e:
14         print "dns resolver error:" +str(e)
15         return
16     for i in A:
17         iplist.append(i.address)
18     return True
19 
20 def checkip(ip):
21     checkurl = ip+":80"
22     getcontent = ""
23     httplib.socket.setdefaulttimeout(5)
24     conn = httplib.HTTPConnection(checkurl)
25 
26     try:
27         conn.request("GET", "/",headers={"Host": appdomain})
28         r = conn.getresponse()
29         getcontent = r.read(50)
30         
31     finally:
32         if getcontent[21:42] == "301 Moved Permanently":
33             print ip+" [OK]"
34         else:
35             print ip+" [Error]"
36 
37 
38 if __name__=="__main__":
39     if get_iplist(appdomain) and len(iplist) > 0:
40         for ip in iplist:
41             checkip(ip)
42     else:
43         print "dns resolver error"

 

posted @ 2018-01-07 11:38  飞奔的小水牛  阅读(254)  评论(0编辑  收藏  举报