keepalived裂脑脚本PY--并发ping包,没有使用等待命令

vim keepalived_nginx.py
i
# coding=utf-8
import os,time,subprocess,threading
def ping(Sip,Dip):
Ip='ping -c 1 -I %s %s'%(Sip,Dip)
p = subprocess.Popen([Ip],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
out = p.stdout.read().decode('utf-8').split(',')
for i in out:
if i.find('received')>0:
return i.split()[0]

class MyThread(threading.Thread):
def __init__(self, func, args):
super(MyThread, self).__init__()
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)

def get_result(self):
try:
return self.result
except Exception:
return None

if __name__ == "__main__":
Sip1 = '192.168.3.224'
Sip2 = '172.16.0.224'
Gip1 = '192.168.3.1'
Dip1 = '192.168.3.225'
Dip2 = '172.16.0.225'
Gip2 = '172.16.0.1'
i = 0
while True:
print()
time.sleep(3)
t1 = MyThread(ping, args=(Sip1, Gip1))
t1.start()
t2 = MyThread(ping, args=(Sip1, Dip1))
t2.start()
t3 = MyThread(ping, args=(Sip2, Dip2))
t3.start()
t4 = MyThread(ping, args=(Sip2, Gip2))
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
i1=int(t1.get_result())
i2=int(t2.get_result())
i3=int(t3.get_result())
i4=int(t4.get_result())
if i1 and i4:
os.system('systemctl start keepalived nginx')
i = 0
if i2 == 0 and i3 == 0:
print('警告,Keepalived主设备内外网都断了\n该设备为主设备\n')
elif i2 == 0 and i3 > 0:
print('警告,主Keepalived外网断开\n该设备为主设备\n')
elif i3 == 0 and i2 >0:
print('警告,主Keepalived内网断开\n该设备为主设备\n')
else:
print('网络正常,该设备是备用')
else:
if i1 == 0:
print('警告,外网断开了\n')
else:
print('警告,内网断开了\n')
os.system('systemctl stop keepalived nginx')
print('nginx和keepalived已停服务\n')
i = 1
continue
posted @ 2020-03-20 01:23  Le1543  阅读(182)  评论(0编辑  收藏  举报