python使用dns轮循检测web服务器是否异常

Posted 标配的小号

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python使用dns轮循检测web服务器是否异常相关的知识,希望对你有一定的参考价值。

我使用的是python2.7,我本来另装了一个python3.6,发现无法安装dnspython,于是只能换回来了
import dns.resolver #这个需要另外下载并安装(下载地址www.dnspython.org/kits/1.9.4/dnspython-1.9.4.tar.gz 解压之后,python setup.py install)
import os
import httplib #因为要用到http?
iplist=[] #存储查到的ip
appdomain="www.baidu.com" #查询的网站服务器
def get_iplist(domain=""): #这应该是说如果domain没有值,则默认为空
try: #捕获异常
A=dns.resolver.query(domain,\'A\')
print (\'hi\')
except Exception,e:
print \'dns wrong:\'+str(e)
return
for i in A.response.answer:
for j in i.items:
print ("ip is %s " % j)
newj=str(j) #如果不转换为字符串格式,会报错
#print type(newj)
iplist.append(newj) #把查询到的ip放到列表中
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) #取头文件的一部分进行对比即可
print getcontent
finally:
if getcontent"": #注意,这里区分大小写,因为是字符串比较
print ip+" [ok]"
else:
print ip+" [error]"
if name
"main":
#if get_iplist(appdomain) and len(iplist)>0:
if get_iplist(appdomain):
for ip in iplist: #逐个检查
checkip(ip)
else:
print "dns resolver error."

以上是关于python使用dns轮循检测web服务器是否异常的主要内容,如果未能解决你的问题,请参考以下文章

Python自动化运维:DNS域名轮循业务监控(IP地址处理模块IPy和DNS处理模块dnspython)

实践:DNS域名轮循业务监控

python3 dns轮询业务检测

搭建分布式系统

DNS域名轮循业务监控

DNS域名轮循业务监控