1 dnspython处理模块的安装,源码方式
wget http://www.dnspython.org/kits/1.9.4/dnspython-1.9.4.tar.gz
tar zxf dnspython-1.9.4.tar.gz
cd dnspython-1.9.4/
python setup.py install
2 解析示例
A记录查询示例
#!/usr/bin/env python # -*- coding: utf-8 -*- import dns.resolver domain = raw_input("请输入一个需要解析的域名:") A = dns.resolver.query(domain,'A') for i in A.response.answer: for j in i.items: if j.rdtype == 1: print j.address
MX记录示例
#!/usr/bin/env python # -*- coding: utf-8 -*- import dns.resolver domain=raw_input('请输入一个域名:') MX=dns.resolver.query(domain,'MX') for i in MX: print i.preference, i.exchange
NS记录示例
import dns.resolver domain=raw_input('请输入一个域名:') NS=dns.resolver.query(domain,'NS') for i in NS.response.answer: for j in i.items: print j.to_text()
CNAME记录示例
import dns.resolver domain=raw_input('请输入一个域名:') cname=dns.resolver.query(domain,'CNAME') for i in cname.response.answer: for j in i.items: print j.to_text()
3 利用dns域名轮训监控业务
监控示例
#!/usr/bin/env python # -*- coding: utf-8 -*- import dns.resolver import os import httplib iplist=[] appdomain="www.ctrip.com" def get_iplist(domain=""): try: A=dns.resolver.query(domain,'A') except Exception,e: print "dns resolver error:"+str(e) 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="" httplib.socket.setdefaulttimeout(5) conn=httplib.HTTPConnection(checkurl) try: conn.request("GET","/",headers={"Host":appdomain}) r=conn.getresponse() getcontent=r.read(15) finally: print getcontent if getcontent=="<!DOCTYPE html>": print ip+":80端口正常 [ok]" else: print ip+":80端口异常 [error]" if __name__=="__main__": if get_iplist(appdomain) and len(iplist)>0: for ip in iplist: checkip(ip) else: print "dns resolver error"
执行 python test1.py
<!DOCTYPE html>
118.89.206.133:80 端口正常 [ok]
原文地址:http://blog.51cto.com/superleedo/2114049