In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about how to use Python to connect telnet to network equipment. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.
Connect the telnet to the network device with Python
0. Preface
Telnet protocol belongs to a kind of TCP/IP protocol family, which is familiar to us network engineers and is often used for remote login to network devices to operate. However, its defect is too obvious, that is, it is not secure, and it is extremely easy to be attacked and stolen information. It is not recommended to use it, but I will start with it in this section.
1. Test environment and key code interpretation
1.1 simple test environment
Using the python3 environment
Use the built-in telnetlib module
A simple experimental environment
Description:
The commands in the cmd.txt file are as follows:
Terminal length 0 show clock show ip interface brief
The IP in the list.txt file is as follows:
192.168.1.101 192.168.1.102 192.168.1.103
1.2 key code
Import xx: import module
Class xx: define a class
Def xx: define function
Try-except: handling possible exceptions
Tn.read_until (expected, timeout=None): wait for expected string or wait timeout
Tn.write (buffer): a string written (meaning to send a command to a device)
Tn.expect (list, timeout=None): read and display, list uses regular expressions (meaning to show the execution process)
Tn.read_very_eager (): read and display (meaning to show the execution process)
Tn.open (host, port=0 [, timeout]): connect the host
Tn.close (): close the connection
Tips: the information delivered by the terminal and the network device is of byte type, so the string encode encoding on the terminal is converted into a byte object, and the byte information echoed by the network device is decoded by decode.
two。 Complete code
Welcome to follow: '333' this platform is for network engineers to share their daily technology and project case experience. In order to consolidate and enhance their technical capabilities and even share what they have learned, engineers are also welcome to share and grow together.'' #! / usr/bin/env python#coding:utf-8' import module 'from telnetlib import Telnetimport timeimport logging' definition class' class TelnetClient (): 'initialization attribute' def _ _ init__ (self): self.tn = Telnet () 'defines the login_host function, which is used to log in to the device' def login_host (self,ip,username,password,enable=None,verbose=True):'to connect the device. Try-except structure 'try: self.tn.open (ip,port=23) except: logging.warning ('% s network connection failed'% ip) return False 'enter user name' self.tn.read_until (bounded Usernameexcept', timeout=1) self.tn.write (b'\ n') self.tn.write (username.encode () + b'\ n') rely = self.tn.expect ([] Timeout=1) [2] .decode () .strip () # read if verbose: print (rely) 'enter user password' self.tn.read_until (bounded PasswordPasswordParse, timeout=1) self.tn.write (password.encode () + b'\ n') rely = self.tn.expect ([] Timeout=1) [2] .decode () .decode () if verbose: print (rely) 'enter privilege mode' if enable is not None: self.tn.write (b'enable\ n') self.tn.write (enable.encode () + b'\ n') if verbose: rely = self.tn.expect ([] Timeout=1) [2] .decode () .strip () print (rely) time.sleep (1) rely = self.tn.read_very_eager () .decode () if 'Login invalid' not in rely: logging.warning (% s login succeeded'% ip) return True else: logging.warning (% s login failed User name or password error'% ip) return False 'defines the do_cmd function to execute the command' def do_cmd (self,cmds): 'read the file The for statement iterates through the command 'with open (cmds) as cmd_obj: for cmd in cmd_obj: self.tn.write (cmd.encode (). Strip () + b'\ n') time.sleep (2) rely = self.tn.read_very_eager (). Decode () logging.warning ('command execution result:\ n% s'% rely) 'defines the logout_host function Close the program 'def logout_host (self): self.tn.close () if _ _ name__ =' _ _ main__': username = 'cisco' # username password =' cisco' # password enable = 'cisco' # privileged password lists =' list.txt' # store IP address file, relative path cmds = 'cmd.txt' # stores the execution command file, relative path telnet_client = TelnetClient ()' reads the file For statement loops into IP' with open (lists,'rt') as list_obj: for ip in list_obj:'if the login result is True, execute the command, and then exit'if telnet_client.login_host (ip.strip (), username,password,enable): telnet_client.do_cmd (cmds) telnet_client.logout_host () time.sleep (2)
3. Running effect
Note: I only store the 192.168.1.101 IP for the effect of this operation, simplify it for the effect.
4. Error reporting effect
Unable to connect remotely
Wrong username and password
5. Fragmentary thoughts
These are just some simple code, there are still many places to be optimized, first for friends to learn, telnet protocol is not safe, the basic network environment is rarely used, ssh is a commonly used protocol, safe and easy to use!
The above is the editor for you to share how to use Python to connect telnet to network devices, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are 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.