Python学习笔记-DNS域名轮循业务监控

来源:互联网 发布:深入理解大数据 pdf 编辑:程序博客网 时间:2024/06/06 03:28

 大部分的DNS解析是一个域名对应一个IP地址,但是通过DNS轮循技术可将一个域名对应多个IP地址,这样可以实现简单且高效的负载平衡,但是轮循技术有一个缺点就是当目标主机不可用时,不能自动的删除,所以引出了要对业务主机的服务的可用性进行监控。

本例通过分析当前域名的解析IP,再结合服务端口探测来实现自动监控,在域名解析中添加、删除IP时,无须对监控脚步更改。

! Python 2.x中的"httplib"模块在Python 3.x中变为"http.client"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/python3
#
import dns.resolver
import os
import http.client
iplist=[] #IP
appdomain="www.google.cn" #
def get_iplist(domain=""): #IPiplist
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 checkip(ip):
checkurl = ip+":80"
getcontent = ""
http.client.socket.setdefaulttimeout(5) #http5
conn = http.client.HTTPConnection(checkurl) #http
try:
conn.request("GET""/"headers = {"Host"appdomain}) #urlhost
r = conn.getresponse()
getcontent = r.read(15) #url15便
finally:
if getcontent == "<!doctype html>": #URL"HTTP200"
print (ip+" [OK]")
else:
print (ip+" [Error]") #
if __name__ == "__main__":
if get_iplist(appdomain) and len(iplist)>0: #IP
for ip in iplist:
checkip(ip)
else:
print ("dns resolver error.")

 

原创粉丝点击