因为公司有两条日常使用线路,电信和香港,香港有时因为运营商问题导致丢包率高,或者不可达时。需要手动切换防火墙上策略路由进行停用线路,使业务可以正常使用。为了方便,使用python进行线路可达判断和操作策略路由。
import paramiko
import time
import os
def Firewall():
status1 = "!!!!!!!!!!!!!!!!!!!HK line alive!!!!!!!!!!!!!!!!!!!!"
status2 = "!!!!!!!!!!!!!!!!!!!HK line unreachable!!!!!!!!!!!!!!!!!"
fping = os.popen("/usr/bin/ping -c 10 IP | grep loss | cut -d ' ' -f 6")
line = fping.read()
pingloss = line.split('%')
pingloss = int(pingloss[0])
standardPing = 25
sshFirewall = paramiko.SSHClient()
sshFirewall.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshFirewall.connect(hostname='防火墙IP', port=端口, username='账号', password='密码',allow_agent=False,look_for_keys=False)
sshConnect = sshFirewall.invoke_shell()
if pingloss < standardPing:
print status1
sshConnect.send('dis policy-based-route rule name hk \n')
sshConnect.send('dis policy-based-route rule name hk_gfw \n')
time.sleep(1)
result = sshConnect.recv(5000).decode()
print result
if 'disable'in result:
sshConnect.send('sys \n')
sshConnect.send('policy-based-route \n')
sshConnect.send('rule name hk \n')
sshConnect.send('enable \n')
sshConnect.send('rule name hk_gfw \n')
sshConnect.send('enable \n')
print '\n ----HK line alive,enable hk and hk_gfw policy routing---- \n'
time.sleep(1)
sshFirewall.close()
else:
print '\n ----HK line alive,hk and hk_gfw policy routing has been enabled,no operation is required---- \n'
sshFirewall.close()
exit()
else:
print status2
sshConnect.send('sys \n')
sshConnect.send('policy-based-route \n')
sshConnect.send('rule name hk \n')
sshConnect.send('disable \n')
sshConnect.send('Y \n')
sshConnect.send('rule name hk_gfw \n')
sshConnect.send('disable \n')
sshConnect.send('Y \n')
time.sleep(1)
result = sshConnect.recv(5000).decode()
print result
print '\n ----HK line unreachable,hk and hk_gfw policy routing disable successful---- \n'
sshFirewall.close()
if __name__ == '__main__':
Firewall()