Purpose: Learn to log in to the switch with a Python script and perform related actions
Environment: Windows 7 Python 3.5.3
The initial reason is because the job needs to query the switch on the IP address of the source port, the constant jump to view the trouble, so decided to write a script, here only to write about using Python and then the available methods.
Telnet is a built-in module with module name Telnetlib.
# define the user name, password, and login device address of the login
Username = ' abc '
Password = ' 123 '
switch_ip = ' 1.2.3.4 '
# connection
Tel_con = Telnetlib. Telnet (switch_ip[, port=23, timeout=10])
# Read recognition and authentication
Tel_con.read_until (' Username: ')
Tel_con.write (username + rn)
Tel_con.read_until (' Password: ')
Tel_con.write (password + rn)
The following can perform the required operation, generally is to identify the ' > ' This symbol, of course, according to the actual situation, the view mode may be other, and read_until may sometimes be executed command return mismatch, then has been waiting, you can use Read_all () Return and then use regular expressions, or delay Time.sleep plus Read_very_eager () method.
Finally remember to exit, switch out with quit, connect to exit with
Tel_con.close ()
Here are a few tips:
1) Set the return error message to rule out the problem Tel_con.set_debuglevel (5), where there are 0-5 levels, the larger the number, the more information.
2) There are cases where the string passed to the Write method requires attention to the encoding
3) Read_until () has a timeout setting, which will return if the time is exceeded, otherwise the script will wait
4) Read_all () may not get EOF and error.
5) There is a need to learn the third-party module Pexpect, it can implement SSH, Telnet, FTP and other interactive automatic login
Here are some references:
Http://www.cnblogs.com/ma6174/archive/2012/05/25/2508378.html
http://blog.csdn.net/oatnehc/article/details/46580753
Https://pypi.python.org/pypi/paramiko
Https://pypi.python.org/pypi/pexpect
This article is from the "Rickyhul" blog, make sure to keep this source http://rickyh.blog.51cto.com/10934856/1947362
Control telnet Login switch with python script