Python脚本:DNS域名轮询监控

所需库

pip3 install dnspython
pip3 install httplib2

代码

#!/usr/bin/python3
import dns.resolver
import http.client
import socket

iplist = []  # 定义域名IP列表
appdomain = "www.google.hk"  # 定义业务域名

def get_iplist(domain=""):  # 域名解析函数
    try:
        A = dns.resolver.resolve(domain, 'A')  # A记录解析类型
        print("DNS query result:", A)  # 打印 DNS 查询结果
    except Exception as e:
        print("DNS resolver error: " + str(e))
        return False
  
    # 检查解析结果是否为空
    if not A.response.answer:
        print("No A records found for domain:", domain)
        return False

    for i in A.response.answer:
        for j in i.items:
            if j.rdtype == dns.rdatatype.A:  # 检查记录类型是否为A记录
                print("Found IP address:", j.address)  # 打印找到的 IP 地址
                iplist.append(j.address)  # 追加
    return True

def check_ip(ip):
    check_ip = ip
    getcontent = ""
    conn = None
  
    try:
        conn = http.client.HTTPConnection(check_ip, 80, timeout=5)  # 创建HTTP连接对象
        conn.request("GET", "/", headers={"Host": appdomain})  # 发起URL请求,并添加主机头
        r = conn.getresponse()
        getcontent = r.read(15)  # 获取URL页面的前15个字符,方便做可用性检测
    except socket.timeout:
        print(ip + " [Timeout]")
    except Exception as e:
        print(ip + " [Error]: " + str(e))
    finally:
        if conn:
            conn.close()
        if getcontent == b"<!doctype html>":  # 检查响应内容
            print(ip + " [OK]")
        else:
            print(ip + " [Error]")

if __name__ == "__main__":
    if get_iplist(appdomain) and len(iplist) > 0:  # 条件:域名正确解析并至少正确返回一个IP
        for ip in iplist:
            check_ip(ip)
    else:
        print("DNS resolver error")

结果

DNS query result: <dns.resolver.Answer object at 0x00000203B6B31CD0>
Found IP address: 173.194.202.199
173.194.202.199 [Timeout]
173.194.202.199 [Error]