dnspython(http://www.dnspython.org/)是Python实现的一个DNS工具包,它支持几乎所有的记录类型,可以用于查询、传输并动态更新ZONE信息,同时支持TSIG(事务签名)验证消息和EDNS0(扩展DNS)。在系统管理方面,我们可以利用其查询功能来实现DNS服务监控以及解析结果的校验,可以代替nslookup及dig等工具,轻松做到与现有平台的整合。
以下脚本实在python3中进行测试的,python2中需要自己稍微变动下!使用下面的脚本时需要安装dnspython和httplib2模块,建议使用源码编译,博主使用pip直接下载时报错了!以下代码的大概思路是先进行域名的解析,查看此域名绑定几个IP地址,然后使用 IP+port 进行访问网站中事先定义好的监控页面。下面是在网站根目录下定义了一个 test.html 页面,内容如下:
<code> [root@feiyu htdocs]# cat test.html <!doctype html> </code>
脚本如下:
<code> #!/usr/bin/python #coding:utf-8 import dns.resolver import os import httplib2 ''' 脚本功能: DNS轮询业务监控脚本 www.tianfeiyu.com ''' iplist = [] #定义域名ip列表变量 appdomain = 'www.tianfeiyu.com' #定义业务域名 def get_iplist(domain=""): #域名解析函数,解析成功追加到iplist try : A = dns.resolver.query(domain,'A') #解析A记录 except Exception as 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 chechip(ip): checkurl = ip+":80" getcontent = "" httplib2.socket.setdefaulttimeout(3) #定义http连接时间 conn = httplib2.HTTPConnectionWithTimeout(checkurl) #创建http连接对象 try: conn.request('GET','/test.html',headers = {'Host':appdomain}) #发起URL请求,添加host主机头,我的测试网页为test.html r = conn.getresponse() #将内容获取到文件中 getcontent = r.read(15) #获取URL页面的前15个字符,以便做校验 finally: result = b'<!doctype html>' if getcontent == result: #监控URL页面的内容一般是事先定义好的 print(ip+' [ok]') else: os.environ['ip'] = str(ip) os.system('echo $ip error!| mail -s montior xxx@xx.com') #发送邮件进行告警 if __name__ == '__main__' : if get_iplist(appdomain) and len(iplist) > 0: #条件:域名解析至少返回一个可用IP for ip in iplist: chechip(ip) else : os.system("echo tianfeiyu's web all dns resolver error!| mail -s montior xxx@xx.com") # 所有ip都无法访问时,发送邮件进行告警 </code>
运行结果为:
<code> [root@feiyu auto]# python dns_monitor.py 115.28.48.187 [ok] </code>
此脚本只是初步完成的,还在不断完善中,欢迎继续关注!