zoukankan      html  css  js  c++  java
  • python3 dns轮询业务检测

    python3中必须使用dnspython3和httplib2!!

    直接安装dnspython3和httplib2

    本脚本源自 刘天斯的《python 自动化运维技术与最佳实践》

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

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

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

    from dns import resolver#dnspython导入方法
    import os
    import httplib2
     
    iplist=[]#定义域名ip列表变量
    appdomain = 'www.baidu.com'#定义业务域名
     
    def get_iplist(domain=""):  ##解析域名为函数,解析成功将追加到iplist
        try:
            A = resolver.query(domain,'A')#解析A记录类型
        except Exception as e:
            print('dns resolver error:' + str(e))
            return
        for i in A:
                iplist.append(i)#追加ip到iplist
        return True
     
    def checkip(ip):#对iplist中IP进行可用检测
        checkurl = str(ip) + ":80"
        getcontent=""
        httplib2.socket.setdefaulttimeout(5)#定义http连接时间超时为5秒
        conn = httplib2.HTTPConnectionWithTimeout(checkurl)#创建http连接对象
     
        try:
            conn.request("GET","/",headers = {"HOST": appdomain}) #发起url请求,添加主机头 ##通过构造html头访问目标业务主机
            response = conn.getresponse()
            getcontent = response.read(15)#获取url前15个字符,做校验用
        finally:
            if getcontent == b"<!DOCTYPE html>" :     ##判断返回字符串是否与预期相同
    #监控url一般事先定义好
    print(str(ip)+'[ok]') else: print(str(ip)+'[error]')#此处可方警告、邮件、短信等 if __name__ =="__main__": if get_iplist(appdomain) and len(iplist) > 0:#域名解析正确至少返回一个ip for ip in iplist: checkip(ip) else: print('dns resolve error')

     测试:

  • 相关阅读:
    hdu 5723 Abandoned country 最小生成树 期望
    OpenJ_POJ C16G Challenge Your Template 迪杰斯特拉
    OpenJ_POJ C16D Extracurricular Sports 打表找规律
    OpenJ_POJ C16B Robot Game 打表找规律
    CCCC 成都信息工程大学游记
    UVALive 6893 The Big Painting hash
    UVALive 6889 City Park 并查集
    UVALive 6888 Ricochet Robots bfs
    UVALive 6886 Golf Bot FFT
    UVALive 6885 Flowery Trails 最短路
  • 原文地址:https://www.cnblogs.com/abels0025/p/11295124.html
Copyright © 2011-2022 走看看