使用python内建模块telnetlib登陆设备
在生成环境中,不推荐使用无加密的telnet来登陆设备,这里只举个简单的例子来演示telnetlib的使用
云配置
云的配置是为了让主机能与交换机互相访问
交换机配置
interface Vlanif1
ip address 192.168.56.2 255.255.255.0
#
aaa
local-user python password cipher 123 //创建python用户,密码为123
local-user python privilege level 15
#
user-interface vty 0 4
authentication-mode aaa
这个时候我们就能与交换机互访了
拓扑
目的
使用telnet登陆python这个用户操作交换机配置loopback 0口地址为1.1.1.1/24
代码
import telnetlib
import time # 可以引入 time 模块,执行后调用 sleep() 函数等待片刻
host = "192.168.56.2" #定义变量存取网元IP、用户名、密码
user = "python"
password = "123"
tn = telnetlib.Telnet(host) #连接登录网元
tn.read_until(b"Username: ",timeout=1) #timeout=1 表示等待的时间,如果1秒内没等到就继续执行,默认是一直等。
tn.write(user.encode('ascii') + b"\n")
tn.read_until(b"Password: ",timeout=1)
tn.write(password.encode('ascii') + b"\n")
tn.write(b"screen-length 0 temporary\n") # 取消分段显示
tn.write(b'sys\n')
tn.write(b"int loopback 0\n")
tn.write(b"ip address 1.1.1.1 24\n")
tn.write(b"return\n") # 返回用户视图,保存配置
tn.write(b"save\n")
tn.write(b"Y\n")
time.sleep(3) # 等待
tn.write(b"quit\n") #打印截屏,此时用 read_very_eager() 能成功
output = tn.read_very_eager().decode('ascii')
print(output)
tn.close() #退出登录
结果