溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python中如何通過腳本進行雙線路切換

發(fā)布時間:2021-11-15 10:50:01 來源:億速云 閱讀:201 作者:小新 欄目:網(wǎng)絡(luò)管理

這篇文章主要為大家展示了“python中如何通過腳本進行雙線路切換”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“python中如何通過腳本進行雙線路切換”這篇文章吧。

    這兩天寫了一個腳本,用于線路切換,目前還有些小bug,還沒有想好邏輯結(jié)構(gòu)如何改,反正想著想著頭發(fā)就沒有了。

要求:1.所有用戶連接ISP是通過Core01的G0/1出局,Core02的G0/1是Shutdown狀態(tài)

       2. 當Core01的G0/1光線線路出問題時,通過腳本去把Core02的G0/1 UP

***更新代碼,增加微信提醒功能

拓撲如下圖:

   python中如何通過腳本進行雙線路切換

腳本如下:

#!/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" 網(wǎng)絡(luò)設(shè)備%s:  無法連接!請確認該設(shè)備IPAddress是否可達!"%ip)  
            return             
        except (EOFError, NetMikoAuthenticationException):
            print(u" 網(wǎng)絡(luò)設(shè)備%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 ="設(shè)備Core01連接互聯(lián)網(wǎng)的端口G0/1已經(jīng)斷開,請管理員確認業(yè)務(wù)。"
        downInterface('172.16.200.21','admin','Password.123')
        upInterface('172.16.200.22','admin','Password.123')
        res02 = 'Intetnet線路已經(jīng)從Core01的G0/1切換至Core02的G0/1端口,請管理員確認業(yè)務(wù)。'
        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= "設(shè)備Core02連接互聯(lián)網(wǎng)的端口G0/1已經(jīng)斷開,請管理員確認業(yè)務(wù)。"
         downInterface('172.16.200.22','admin','Password.123')
         upInterface('172.16.200.21','admin','Password.123')
         res02='Internet線路已經(jīng)從Core02的G0/1切換至Core01的G0/1端口,請管理員確認業(yè)務(wù)。'
         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'))	

主備設(shè)備的目前狀態(tài)如下:所有流量從Core01的G0/1出局

python中如何通過腳本進行雙線路切換

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

python中如何通過腳本進行雙線路切換

從互聯(lián)網(wǎng)ISP去Ping 企業(yè)的IP: 169.254.100.1狀態(tài)是OK的。

python中如何通過腳本進行雙線路切換

以下是測試抓取日志以及線路切換后互聯(lián)網(wǎng)ISP去ping 企業(yè)的IP: 169.100.1狀態(tài)

Core01連接互聯(lián)網(wǎng)的端口已經(jīng)斷開

python中如何通過腳本進行雙線路切換

Core02通過腳本自動切換

python中如何通過腳本進行雙線路切換

從ISP的路由器去ping企業(yè)的IP: 169.254.100.1的狀態(tài):

python中如何通過腳本進行雙線路切換

監(jiān)控腳本運行的結(jié)果:

python中如何通過腳本進行雙線路切換

---------------------------------------------------------------------------------------------------------------------------

下面再從Core02自動切換回Core01

python中如何通過腳本進行雙線路切換

Core01日志狀態(tài)

python中如何通過腳本進行雙線路切換

ISP去Ping 企業(yè)的IP: 169.254.100.1的狀態(tài):

python中如何通過腳本進行雙線路切換

腳本運行的狀態(tài):

python中如何通過腳本進行雙線路切換

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

python中如何通過腳本進行雙線路切換

以上是“python中如何通過腳本進行雙線路切換”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI