python DNS域名轮询业务监控

应用场景:

    目前DNS支持一个域名对应多个IP的解析,优势是可以起到负载均衡的作用,最大的问题是目标主机不可用时无法自动剔除,因此必须在自己的业务端写好监控与发现,怎么样来做这样的监控,以python为例,使用的是dnspython模块,通过dnspython模块解析出域名的A记录 IP地址,然后使用http 80端口探测该IP是否正常

1 安装

pip dnspython

2 代码展示:

#!/usr/bin/env python
#_*_coding:utf-8 _*_
#__author__:Davidlua

import dns.resolver
import os
import httplib

iplist = [] #定义域名IP列表变量
appdomain = "www.baidu.com" #定义目标域名

def get_iplist(domain=""):
"""域名解析函数,解析成功IP追加到iplist"""
try:
A = dns.resolver.query(domain,'A') #解析A记录
except Exception,e:
print "dns resolver error:" +str(e)
return
for i in A.response.answer: #使用responese.answer方法
for j in i.items:
iplist.append(j) #追加到iplist
return True

def checkip(ip):
oip = ('%s') % ip #将解析的Ip转为字符串格式,以便跟:80端口合并
checkurl = oip+":80"
getcontent = ""
httplib.socket.setdefaulttimeout(5) #定义http链接超时时间
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 == "<!DOCTYPE html>": #监控url页面的类型要先查清楚,在做对比,这里<!DOCTYPE html>要大写,也可以对比http状态码
print oip+" [ok]"
else:
print oip+" [error]" #这里可以放置告警程序,比如发短信,邮件等

if __name__ == "__main__":
if get_iplist(appdomain) and len(iplist) > 0: #域名解析正确,且不少于1个IP
for ip in iplist:
checkip(ip)
else:
print "dns resolver error."

3 结果展示

C:Python27python.exe D:/python/github/miniwanmonitor/domen.py
www.a.shifen.com. [ok]
14.215.177.38 [ok]
14.215.177.39 [ok]
dns resolver error.

Process finished with exit code 0

原文地址:https://www.cnblogs.com/rayong/p/7911033.html