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中如何通过脚本进行双线路切换

相关内容

热门资讯

欧盟对俄制裁列单中企,中国驻欧... 问:2026年7月23日,欧盟通过第21轮对俄罗斯制裁方案,新增列单制裁中国企业。中方对此有何评论?...
特朗普预警9月政府“停摆”,美... 一国总统公开预警自家联邦政府即将“停摆”,这种魔幻剧情又双叒叕要在华盛顿上演?当地时间7月22日,特...
视频丨2026年APEC数字和... 昨天(23日),2026年亚太经合组织数字和人工智能部长会议在四川成都举行。本届会议的主题为“数字和...
海南商发二期发射区土建完工,建... 7 月 24 日消息,海南商发今日宣布,海南商业航天发射场二期发射区建设项目土建工作完成,全面转入设...
菲律宾,没有以色列的命,得了以... 菲律宾,马尼拉。美国国务卿鲁比奥来了。菲律宾期盼已久的“救星”来了。菲律宾认为的“阳光”来了。从机场...
服务器盛会东莞启幕,松山湖软硬... 7月23日至24日,“智算筑基 融链共赢——2026年服务器产业供需对接活动”在东莞举行。作为系列配...
面向6G通信、高端安检、精准医... 太赫兹作为“电磁波段最后一块未开垦之地”,近年在超快光电子、低尺度半导体技术的推动下,逐步从实验室走...
获得全球最高奖项的中国数学家,... 一个喜欢玩梗的二次元大佬,竟然站上了数学界最高荣誉的领奖台。他就是今年的菲尔兹奖得主之一,邓煜。另一...
单向空间杭州旗舰店8年后谢幕,... 去年12月,单向空间杭州乐堤港店员工回应闭店谣言,称“没有收到任何闭店通知”。不到一年,停止营业的消...
带娃家长刷不到下铺,算法不该把... 据新华社的报道,一位宝妈带4岁娃要从昭通去杭州南,在12306上购票时反复被分到上铺,一天内取消三次...