Dnspython模块
1.模块域名解析方法
A记录,主机名转换成IP地址
MX记录,邮件交换记录,定义邮件服务器的域名
CNAME记录,别名记录,实现域名间的映射
NS记录,标记区域的域名服务器及授权子域
PTR记录,反向解析,与A记录相反,将IP转换成主机名
SOA记录,SOA标记,一个起始授权区的定义
2.常见解析类型示例说明
实现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
220.181.111.86
123.125.114.144
220.181.111.85
MX记录
import dns.resolver
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
MX preference = 20 mail exchanger = jpmx.baidu.com.
MX preference = 20 mail exchanger = mx50.baidu.com.
MX preference = 10 mail exchanger = mx.n.shifen.com.
MX preference = 20 mail exchanger = mx1.baidu.com.
NS记录
import dns.resolver
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()
ns4.baidu.com.
dns.baidu.com.
ns7.baidu.com.
ns2.baidu.com.
ns3.baidu.com.
CNAME记录
import dns.resolver
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()
2.DNS域名轮询业务监控
大部分的DNS解析都是一个域名对应一个IP,但通过DNS轮询技术可以做到一个域名对应多个IP,从而实现最简单且高效的负载均衡,不过此方案的最大弊端是目标主机不可用时无法被自动剔除,因此做好业务主机的服务可监控至关重要。本示例通过分析天谴域名的解析IP,再结合服务端口探测来实现自动监控,在域名解析中添加、删除IP时,无须对监控脚本进行修改。
(1)步骤
实现域名的解析,获取域名所有的A记录解析IP列表
对IP列表进行HTTP级别的探测
#!/usr/bin/env python import dns.resolver import os import httplib iplist = [] appdomain = ‘163.com‘ def get_iplist(domain = ""): try: A = dns.resolver.query(domain,‘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) 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: if getcontent == "<!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."