#!/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)