1、安装库
windows开启telnet服务就行
2、函数介绍
1.引入telnetlib模块和时间模块
import telnetlib
import tim
2.调用telnetlib的telnet()函数,将它赋值给tn,尝试以telnet方式登录交换机。
host='10.0.1.x'
tn=telnetlib.Telnet(host)
- tn.read_until(‘Password:’) 的函数来告诉程序:如果在终端信息库读到’‘Password:’‘字样,则使用tn.write(password+’\n’)函数来输入telnet密码并回车
tn.read_until(b'Password:')
tn.write(password.encode('ascii')+b'\n')
print('成功登录到交换机:'+host)
4.用Telnetlib的write()函数在SW1上输入各种配置命令了,这里给交换机配置MSTP。
tn.write(b'sys\n')
tn.write(b'stp mode rstp\n')
#保存配置
tn.write(b'return\n')
tn.write(b'save\n')
tn.write(b'y\n')
tn.write(b'dis stp | include CIST Global Info\n')
time.sleep(1)
5…打印终端回显消息
output=tn.read_very_eager().decode('ascii')
print(output)
6.关闭
tn.close()#关闭连接
3、代码编写
import telnetlib
import time
# 配置选项
Host = '192.168.73.176' # Telnet服务器IP
username = 'z' # 登录用户名
password = 'z' # 登录密码
# 连接Telnet服务器
tn = telnetlib.Telnet(Host)
# 输入登录用户名
tn.read_until(b'login:')
tn.write(username.encode('ascii') + b"\n")
# 输入登录密码
tn.read_until(b'Password:')
tn.write(password.encode('ascii') + b"\n")
print('成功登录到设备:'+Host)
# 登录完毕后,执行ls命令
tn.read_until(b':~$ ')
print("执行pwd")
tn.write(b'pwd\n')
time.sleep(1)
output=tn.read_very_eager().decode('ascii')
print(output)
# ls命令执行完毕后,终止Telnet连接(或输入exit退出)
tn.read_until(b':~$ ')
tn.close() # tn.write('exit\n')
执行结果