本脚本源自 刘天斯的《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脚本。该脚本通过DNS解析获取目标域名的IP地址列表,并通过模拟HTTP请求来验证这些IP地址上的服务是否正常运行。具体实现包括DNS解析、HTTP请求及响应头部对比等步骤。
865

被折叠的 条评论
为什么被折叠?



