In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you "how to switch two lines through script in python". The content is easy to understand and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to switch two lines through script in python".
These two days wrote a script for line switching, there are still some small bug, have not figured out how to change the logical structure, anyway, thinking about the hair is gone.
Requirements: 1. All users who connect to ISP are out of the game through Core01's G0swap 1, and Core02's G0Unip 1 is Shutdown status.
two。 When there is something wrong with the G0Uniq1 ray line of Core01, use a script to change the G0Uniq1 UP of Core02.
* update the code to add Wechat reminder function
The topology is shown in the following figure:
The script is as follows:
#! / usr/bin/env python3#-*-coding: utf-8-*-import timeimport reimport sysimport subprocess from sendwxInfo import * from netmiko import ConnectHandlerfrom netmiko.ssh_exception import NetMikoTimeoutException,NetMikoAuthenticationExceptiondef 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 "network device% s: unable to connect! Please confirm whether the IPAddress of the device is reachable! " % ip) return except (EOFError, NetMikoAuthenticationException): print (u "Network device% s: wrong username and password! please confirm your account number and password!" % ip) return res = Conn (ip,username,password,connect) return res return wrapper@authdef upInterface (ip,username,password,connect): cmd = ['interface g0lemagna no shutdown'] connect.send_config_set (cmd) res = connect.send_command (' show ip int brief') connect.disconnect () @ authdef downInterface (ip,username,password,connect): cmd = ['interface g0gamma 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 = "the device Core01's Internet connection port G0Action1 has been disconnected. Ask the administrator to confirm the business. " DownInterface ('172.16.200.21) upInterface (' 172.16.200.22) Password.123') res02 = 'Intetnet line has been switched from G0Univer 1 of Core01 to port G0 of Core02, please confirm the business.' Res03 = 'important information!' 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= "device Core02 connection to the Internet port G0Bank 1 has been disconnected Ask the administrator to confirm the business. " DownInterface ('172.16.200.22) upInterface (' 172.16.200.21) Password.123) res02='Internet lines have been switched from G0Universe 1 of Core02 to port G0ap1 of Core01. Please confirm the business.' Res03 = 'important information!' 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)
Wechat reminder function code
#! / usr/bin/env python3 #-*-coding: utf-8-*-import urllib,jsonimport urllib.parseimport urllib.requestimport sysclass WeChat (object): _ _ token_id =''def _ init__ (self) Url): self.__url = url.rstrip ('/') # change yourself 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: 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': ", # change' toparty':" XXX ", 'msgtype':" text ") # change 'agentid': "XXXXXX",' text': {'content':message} "by yourself 'safe': "0}, ensure_ascii=False) response = self.postData (data.encode (' utf-8'))
The current status of the active and standby equipment is as follows: all traffic is outgoing from Core01 G0ap1.
The G0Uniq1 port of the standby router Core02 is closed. (note: the G0Uniq1 configuration of Core01 is the same as that of Core02.)
From the Internet ISP to the Ping enterprise IP: 169.254.100.1 status is OK.
The following is the test crawl log and the IP of the Internet ISP to ping enterprise after line switching: 169.100.1 status
The port of Core01 connected to the Internet has been disconnected
Core02 is automatically switched by script
From ISP's router to ping Enterprise's IP: 169.254.100.1 status:
Monitor the results of the script run:
-
Next, automatically switch from Core02 to Core01.
Core01 log status
ISP to Ping Enterprise IP: 169.254.100.1 status:
The status of the script running:
* added Wechat reminder function
The above is all the contents of the article "how to switch two lines through a script in python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.