您的位置:首页 > 编程语言 > Python开发

python 基于dns 轮询的业务检测

2015-09-01 17:18 731 查看
本脚本源自 刘天斯的《python 自动化运维技术与最佳实践》

该脚本功能为判断业务是否正常。过程为:首先脚本会向dns服务器提出解析请求,拿到请求返回结果后(一个域名返回多个A记录)

通过模仿浏览器访问业务ip,比对返回的html头是否与预期头相同,进而判断业务是否正常。

在文中脚本使用python2 缩写,在python3 下几乎不可运行。稍加改动脚本如下:

import dns.resolver
import os
import httplib2

iplist=[]
appdomain = 'www.baidu.com'

def get_iplist(domain=""):                                           ##解析域名为多个ip
try:
A = dns.resolver.query(domain,'A')
except Exception as e:
print('dns resolver error:' + str(e))
return
for i in A:
iplist.append(i)
return True

def checkip(ip):
checkurl = str(ip) + ":80"
getcontent=""
httplib2.socket.setdefaulttimeout(5)
conn = httplib2.HTTPConnectionWithTimeout(checkurl)

try:
conn.request("GET","/",headers = {"HOST": appdomain})                    ##通过构造html头访问目标业务主机
response = conn.getresponse()
getcontent = response.read(15)
finally:
if getcontent == b"<!DOCTYPE html>" :                                ##判断返回字符串是否与预期相同
print(str(ip)+'[ok]')
else:
print(str(ip)+'[error]')
if __name__ =="__main__":
if get_iplist(appdomain) and len(iplist) > 0:
for ip in iplist:
checkip(ip)
else:
print('dns resolve error')


文中使用的python LIB 包,dnspython 与httplib 使用pip install 直接安装均报错。

在dnspython 官网下载dnspython 包:

http://www.dnspython.org/
然后使用pip install 安装。

httplib 在python3 中命名为httplib2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python