DNS
dnspython(http://www.dnspython.org/) 是Python实现的一个DNS工具包,它支持几乎所有的记录类型,可以用于查询、传输并动态更新ZONE信息,同时支持TSIG(事务签名)验证消息和EDNS0(扩展DNS).在系统方面,我们可以利用其查询功能来实现DNS服务监控以及解析结果的校验,可以代替nslookup及dig等工具,轻松做到与现有平台的整合
安装
pip install dnspython
DNS记录解析
- A记录,将主机名转换成IP地址
- MX记录,邮件交换记录,定义邮件服务器的域名
- CNAME记录,指别名记录,实现域名间的映射
- NS记录,标记区域的域名服务器及授权子域
- PTR记录,反向解析,与A记录相反,将IP转换成主机名
- SOA记录,SOA标记,一个起始授权区的定义
A记录
# codeing=utf-8
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
MX记录
# coding=utf-8
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
Please input an domain: 163.com
MX preference = 10 mail exchanger = 163mx02.mxmail.netease.com.
MX preference = 10 mail exchanger = 163mx01.mxmail.netease.com.
MX preference = 50 mail exchanger = 163mx00.mxmail.netease.com.
MX preference = 10 mail exchanger = 163mx03.mxmail.netease.com.
NS记录
# coding=utf-8
import dns.resolver
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()
*************NS****************
Please input an domain: baidu.com
ns4.baidu.com.
dns.baidu.com.
ns2.baidu.com.
ns7.baidu.com.
ns3.baidu.com.
CNAME记录
# coding=utf-8
import dns.resolver
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()
****************CNAME****************
Please input an domain: www.baidu.com
www.a.shifen.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."