zoukankan      html  css  js  c++  java
  • 批量监测dns是否可用脚本,不可用时并切换

    #!/usr/bin/env python
    # coding=utf-8
    # hexm@2016-02-14
    
    import time
    import requests
    import paramiko
    import subprocess
    import requests
    
    HOST = (
            "10.88.2.182:22",
         "10.88.2.183:22",
        "10.88.2.184:22"
    )
    class DnsHelper(object):
    
        def checkStatus(self, dns):
            '''
            检查状态
            '''
            status = subprocess.call('/usr/bin/dig www.baidu.com @%s +time=1 &> /dev/null' % dns, shell=True)
            return status
    
        def modifyStatus(self):
            NS = "nameserver %s
    nameserver %s
    nameserver %s" % (DNS[0], DNS[1], DNS[2])
            cmd = "echo "%s" > /etc/resolv.conf" % NS
            self.exec_command(cmd)
    
        def exec_command(self, cmd):
            '''
            远程连接修改
    
            '''
            private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            for host in HOST:
                h,p = host.strip().split(':')
                try:
                    ssh.connect(hostname=h, port=int(p), username='root', pkey=private_key, timeout=1)
                    stdin, stdout, stderr = ssh.exec_command(cmd)
                except:
                    continue
                ssh.close()
            self.alarm("切换dns为%s成功" % DNS[0])
    
        def alarm(self, info):
            url = "http://alarm.mingxiao.com/alarm/index.php?type=13&gid=199&msg=%s" % info 
            try:
                r = requests.get(url)
            except:
                pass
    
    if __name__ == "__main__":
        TAG = 0  # 标志位,0正常,其他不正常
        DNS = ["202.106.0.20", "119.29.29.29", "223.5.5.5"]
    
        obj = DnsHelper()
        while True:
            for i in range(2):  # 两次次状态是否为0, 0正常,其他不正常
                status = obj.checkStatus(DNS[0])
            print(status,TAG,DNS)
                if status != 0:
                    TAG += 1
                time.sleep(10) 
            if TAG != 0:  # 检测一次不正常,切换dns
                TAG = 0
                obj.alarm('DNS %s 检测不正常,正在切换' % DNS[0])
                DNS.append(DNS[0])  
                DNS.remove(DNS[0])  # 不正常的DNS放到末尾,
                status = obj.checkStatus(DNS[0])  # 检查新DNS是否正常
                if status == 0:  # 正常则切换dns
                    obj.modifyStatus()
                    #TAG = 0
        time.sleep(300)
  • 相关阅读:
    转:一道笔试题-将int型数组强制转换为char*,再求strlen,涉及大小端
    转:git windows中文 乱码问题解决汇总
    git教程1
    刘汝佳黑书 pku等oj题目
    C/C++ qsort()快速排序用法
    char s[]字串和char *s字串有什麼区别?
    c语言‘’ ,‘0’, “0” ,0之间的区别
    带符号的char类型取值范围为什么是-128——127
    c语言memset详解
    【线性规划与网络流24题】孤岛营救问题 分层图
  • 原文地址:https://www.cnblogs.com/xiaoming279/p/6399234.html
Copyright © 2011-2022 走看看