這篇文章主要為大家展示了“python中如何通過腳本進行雙線路切換”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“python中如何通過腳本進行雙線路切換”這篇文章吧。
這兩天寫了一個腳本,用于線路切換,目前還有些小bug,還沒有想好邏輯結構如何改,反正想著想著頭發就沒有了。
要求:1.所有用戶連接ISP是通過Core01的G0/1出局,Core02的G0/1是Shutdown狀態
2. 當Core01的G0/1光線線路出問題時,通過腳本去把Core02的G0/1 UP
***更新代碼,增加微信提醒功能
拓撲如下圖:

腳本如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import re
import sys
import subprocess
from sendwxInfo import *
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException,NetMikoAuthenticationException
def auth(Conn):
def wrapper(ip,username,password):
device = {
'device_type': 'cisco_ios',
'ip': ip,
'username': username,
'password': password,
}
try:
connect = ConnectHandler(**device)
connect.enable()
except (EOFError, NetMikoTimeoutException):
print(u" 網絡設備%s: 無法連接!請確認該設備IPAddress是否可達!"%ip)
return
except (EOFError, NetMikoAuthenticationException):
print(u" 網絡設備%s: 用戶名與密碼錯誤!請確認賬號與密碼!" %ip)
return
res = Conn(ip,username,password,connect)
return res
return wrapper
@auth
def upInterface(ip,username,password,connect):
cmd = ['interface g0/1','no shutdown']
connect.send_config_set(cmd)
res = connect.send_command('show ip int brief')
connect.disconnect()
@auth
def downInterface(ip,username,password,connect):
cmd = ['interface g0/1','shutdown']
connect.send_config_set(cmd)
connect.disconnect()
def sendInfo():
weixinInfo = WeChat('https://qyapi.weixin.qq.com/cgi-bin')
return weixinInfo
def masterLogs():
filename = '/var/log/syslog-ng/172.16.200.21/messages'
file = subprocess.Popen('tail -n 1 ' +filename , shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
masterData = str(file.stdout.readline(),encoding='utf-8')
if re.match('.*sla 1 state Up -> Down.*',masterData):
res01 ="設備Core01連接互聯網的端口G0/1已經斷開,請管理員確認業務。"
downInterface('172.16.200.21','admin','Password.123')
upInterface('172.16.200.22','admin','Password.123')
res02 = 'Intetnet線路已經從Core01的G0/1切換至Core02的G0/1端口,請管理員確認業務。'
res03 = '重要信息!'
message = "{0}\n{1}\n\n{2}".format(res03,res01,res02)
info = sendInfo()
info.sendMessage(message)
def slaveLogs():
filename = '/var/log/syslog-ng/172.16.200.22/messages'
file = subprocess.Popen('tail -n 1 ' +filename , shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
slaveData = str(file.stdout.readline(),encoding='utf-8')
if re.match('.*sla 1 state Up -> Down.*',slaveData):
res01= "設備Core02連接互聯網的端口G0/1已經斷開,請管理員確認業務。"
downInterface('172.16.200.22','admin','Password.123')
upInterface('172.16.200.21','admin','Password.123')
res02='Internet線路已經從Core02的G0/1切換至Core01的G0/1端口,請管理員確認業務。'
res03 = '重要信息!'
message = "{0}\n{1}\n\n{2}".format(res03,res01,res02)
info = sendInfo()
info.sendMessage(message)
if __name__ == "__main__":
while True:
masterLogs()
time.sleep(5)
slaveLogs()
time.sleep(5)微信提醒功能代碼
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib,json
import urllib.parse
import urllib.request
import sys
class WeChat(object):
__token_id = ''
def __init__(self,url):
self.__url = url.rstrip('/')
#自行更改
self.__corpid = 'XXXXXXXXXX'
self.__secret = 'XXXXXXXXXXXXXX'
def authID(self):
params = {'corpid':self.__corpid, 'corpsecret':self.__secret}
data = urllib.parse.urlencode(params)
content = self.getToken(data)
try:
self.__token_id = content['access_token']
except KeyError:
raise KeyError
def getToken(self,data,url_prefix='/'):
url = self.__url + url_prefix + 'gettoken?'
try:
response = urllib.request.Request(url + data)
except KeyError:
raise KeyError
result = urllib.request.urlopen(response)
content = json.loads(result.read())
return content
def postData(self,data,url_prefix='/'):
url = self.__url + url_prefix + 'message/send?access_token=%s' % self.__token_id
request = urllib.request.Request(url,data)
try:
result = urllib.request.urlopen(request)
except urllib.request.HTTPError as e:
if hasattr(e,'reason'):
print ('reason',e.reason)
elif hasattr(e,'code'):
print ('code',e.code)
return 0
else:
content = json.loads(result.read())
result.close()
return content
def sendMessage(self,message):
self.authID()
data = json.dumps({
'touser':"",
#自行更改
'toparty':"XXX",
'msgtype':"text",
#自行更改
'agentid':"XXXXXX",
'text':{
'content':message
},
'safe':"0"
},ensure_ascii=False)
response = self.postData(data.encode('utf-8')) 主備設備的目前狀態如下:所有流量從Core01的G0/1出局

備用路由器Core02的G0/1口是關閉狀態,(注意一點: Core01與Core02各自的G0/1配置相同)

從互聯網ISP去Ping 企業的IP: 169.254.100.1狀態是OK的。

以下是測試抓取日志以及線路切換后互聯網ISP去ping 企業的IP: 169.100.1狀態
Core01連接互聯網的端口已經斷開

Core02通過腳本自動切換

從ISP的路由器去ping企業的IP: 169.254.100.1的狀態:

監控腳本運行的結果:

---------------------------------------------------------------------------------------------------------------------------
下面再從Core02自動切換回Core01

Core01日志狀態

ISP去Ping 企業的IP: 169.254.100.1的狀態:

腳本運行的狀態:

****添加的微信提醒功能

以上是“python中如何通過腳本進行雙線路切換”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。