【Python】DNS域名轮循业务监控

应用背景:

大部分的DNS解析都是一个域名对应一个IP地址,但通过DNS轮循技术可以做到一个域名对应多个IP,从而实现负载均衡,减轻服务器压力,不过此方案的最大弊端是目标主机不可用时无法被自动剔除,因此做好业务主机的服务可用监控至关重要

步骤:

  • 安装dnspython模块:pip install dnspython
  • 获取域名所有的A记录解析IP列表
  • 对所有IP进行HTTP级别的探测
#-*- coding: utf-8 -*- 
#!/usr/bin/python

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:
        for j in i.items:
            iplist.append(j.address)    #追加到iplist
    return True

def checkip(ip):
    checkurl=ip+":80"
    getcontent=""
    httplib.socket.setdefaulttimeout(5)    #定义http连接超时时间(5秒)
    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页的内容一般是事先定义好,比如“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."


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值