【Python自动化运维】DNS轮询技术

DNS轮询技术主要先解析出所有主机,然后可通过http请求方式测试主机,再决定是否将请求发送到此主机,实现负载均衡。

结构图如下:

图.1

DNS域名解析代码清单:

具体实现转发请求不实现

#!/usr/bin/python
#-*- coding: utf-8 -*-
import sys
import dns.resolver
import httplib

IP=[]

def Get_IP_List(domain=""):
    AB = None    
    try:
        AB = dns.resolver.query(domain, 'A')
    except Exception,e:
        print "dns.resolver.query:",str(e)
    finally:
        if AB is not None:
            for i in AB.response.answer:
                for j in i.items:
            #query第二个参数明明指定是返回'A'记录,测试了一下www.baidu.com,居然'CNAME'也返回了,增加异常处理
                #print type(j)
                    try:
                        IP.append(j.address)
                    except Exception,e:
                        continue
    return True

def Check_IP(ip, i):
    checkurl = ip+":80"
    httplib.socket.setdefaulttimeout(5)
    conn = httplib.HTTPConnection(checkurl)
    ret = None
    content = None    
    try:
        conn.request("GET", "/", headers={"Host":sys.argv[i]})
        ret = conn.getresponse()
        content = ret.read(15)
    finally:
        if content == "<!DOCTYPE HTML>" or content == "<!doctype html>":
            print ip+" [OK]"
        else:
            print ip+" [ERROR]"

if __name__ == "__main__":
    arglen = len(sys.argv)
    for i in range(1,arglen):
        print "-"*20
        print sys.argv[i]
        Get_IP_List(sys.argv[i])
        for ip in IP:
            Check_IP(ip, i)
        print "-"*20


你可能感兴趣的:(python,负载均衡,测试,dns)