python中如何通过脚本进行双线路切换
admin
2023-02-18 06:00:10
0

    这两天写了一个脚本,用于线路切换,目前还有些小bug,还没有想好逻辑结构如何改,反正想着想着头发就没有了。

要求:1.所有用户连接ISP是通过Core01的G0/1出局,Core02的G0/1是Shutdown状态

       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" 网络设备%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出局

python中如何通过脚本进行双线路切换

备用路由器Core02的G0/1口是关闭状态,(注意一点: Core01与Core02各自的G0/1配置相同)

python中如何通过脚本进行双线路切换

从互联网ISP去Ping 企业的IP: 169.254.100.1状态是OK的。

python中如何通过脚本进行双线路切换

以下是测试抓取日志以及线路切换后互联网ISP去ping 企业的IP: 169.100.1状态

Core01连接互联网的端口已经断开

python中如何通过脚本进行双线路切换

Core02通过脚本自动切换

python中如何通过脚本进行双线路切换

从ISP的路由器去ping企业的IP: 169.254.100.1的状态:

python中如何通过脚本进行双线路切换

监控脚本运行的结果:

python中如何通过脚本进行双线路切换

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

下面再从Core02自动切换回Core01

python中如何通过脚本进行双线路切换

Core01日志状态

python中如何通过脚本进行双线路切换

ISP去Ping 企业的IP: 169.254.100.1的状态:

python中如何通过脚本进行双线路切换

脚本运行的状态:

python中如何通过脚本进行双线路切换

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

python中如何通过脚本进行双线路切换

相关内容

热门资讯

进口马铃薯“逐颗检查”?岛内名... 海峡导报综合报道 新党籍台北市议员侯汉廷指控,民进党为配合“台美贸易协定(ART)”,放宽174项农...
燃气灶的火为什么会突然灭掉 原因是燃气灶的电池没有电了,需要拆掉电池盒更换一个新的电池;还有可能是燃气用完了,可以充值燃气;还有...
燃气灶的控制器坏了怎么修 控制器内部都是由复杂的电子元件组成的,所以当燃气灶的电子控制器坏了,一般都是需要直接更换燃气灶的控制...
燃气灶为什么外圈蓝火苗内圈红火... 燃气灶充分燃烧的情况下应该是呈蓝色火焰,这个时候产生的热能值最高,也最安全。出现“红火”主要是以下原...
燃气灶一用中间就没火是什么原因 原因可能是电池没电了,建议更换电池解决一下;还有就是点火针发方向可能倾斜,建议调整点火针的方向,对准...
燃气灶为什么外圈没火 原因可能是因为点火针位置不当,通常情况下点火针与火盖之间的距离控制在4至6毫米,且需要对准火孔,而且...
批民进党当局完全脱离民意,蓝营... 海峡导报综合报道 国民党台北市议员参选人李明璇6日提及台湾地区领导人赖清德以及台行政机构负责人卓荣泰...
五月天“宠己”正当时 【核心提示】消费是经济发展的晴雨表。如今,有人为一场演唱会奔赴一座城;有人心甘情愿为宠物买单;也有人...
全国智能化医疗器械标准化工作组... 【大河财立方消息】近日,市场监管总局批准筹建全国智能化医疗器械标准化工作组,由国家药监局负责管理。全...
中原追风记①丨风电“三大件”齐... 【开栏的话】风光无限的中国,有一个“追风”的河南。广袤的中原大地之上,无论田野与山间,巍然挺立着一道...