Python网络自动化运维实验-telnet
(本博客借鉴《网络工程师的python之路》这本书)
实验环境
采用思科平台gns3。IP地址已经写好,所有路由器的账号和密码都已提前配置好。用户登录直接是等级15,不需要输入enable密码。
在这个环境中,cloud1连接的虚拟机centos 7.6系统。
确保centos与R1 R2之间能ping通。
实验需求
用telnetlib模块登录到R1和R2,配置环回接口 loopback1的IP地址为 1.1.1.1和2.2.2.2。刚开始设备里没有环回接口。
实验脚本和结果
脚本
[root@mty xin]# cat telnet.py
import telnetlib
host=['192.168.148.11','192.168.148.12']
user='aaa'
password1='bbb'
a=0
for i in host:
tn=telnetlib.Telnet(host[a])
tn.read_until(b"Username:")
tn.write(user.encode('ascii')+b"\n")
tn.read_until(b"Password:")
tn.write(password1.encode('ascii')+b"\n")
tn.write(b"conf t\n")
tn.write(b"int loopback 3\n")
if i=='192.168.148.11':
tn.write(b"ip add 1.1.1.1 255.255.255.255\n")
else:
tn.write(b"ip add 2.2.2.2 255.255.255.255\n")
tn.write(b"end\n")
tn.write(b"exit\n")
print(tn.read_all().decode('ascii'))
a=a+1
回显结果:
[root@mty xin]# python telnet.py
R1#conf t
Enter configuration commands, one per line. End with CNTL/Z.
R1(config)#int loopback 3
R1(config-if)#ip add 1.1.1.1 255.255.255.255
R1(config-if)#end
R1#exit
R2#conf t
Enter configuration commands, one per line. End with CNTL/Z.
R2(config)#int loopback 3
R2(config-if)#ip add 2.2.2.2 255.255.255.255
R2(config-if)#end
R2#exit
R1 R2结果
脚本分析
在python3中使用telnetlib需要注意一下几点:
- 在字符串的前面加上b。
- 在变量和telnetlib函数后面需要加上.encode(‘ascii’)函数。
- 在read_all()函数后面需要加上decode(‘ascii’)函数。
- python2则不需要上面三条。
分析
import telnetlib
调用telnetlib模块完成telnet的功能。
host=['192.168.148.11','192.168.148.12']
user='aaa'
password1='bbb'
a=0
定义两个用于登录的ip地址,放在列表便于遍历。定义用户名和密码。a=0是用来配合遍历ip地址的。
for i in host:
tn=telnetlib.Telnet(host[a])
遍历第一个ip地址,然后登录上去。
tn.read_until(b"Username:")
tn.write(user.encode('ascii')+b"\n")
tn.read_until(b"Password:")
tn.write(password1.encode('ascii')+b"\n")
输入提前定义好的用户名和密码。然后因为是字符串所以前面加’b’,因为调用了变量user和password1所以跟上.encode(‘ascii’)。
意思是当读取到"Username: “输入"aaa”。当读取到"Password:“输入"bbb”。
tn.write(b"conf t\n")
tn.write(b"int loopback 3\n")
进入到loopback3接口
if i=='192.168.148.11':
tn.write(b"ip add 1.1.1.1 255.255.255.255\n")
else:
tn.write(b"ip add 2.2.2.2 255.255.255.255\n")
第一遍遍历的是192.168.148.11这个ip地址,第二遍是192.168.148.12这个p地址。按照需求给R1配 1.1.1.1,给R2配2.2.2.2。
tn.write(b"end\n")
tn.write(b"exit\n")
第一个end是回到#模式。
第二个exit是退出telnet模式。
如果不退出telnet模式,则结尾的 print(tn.read_all().decode(‘ascii’))不生效。
print(tn.read_all().decode('ascii'))
把执行的命令回显到centos的窗口。必须退出telnet。
a=a+1
最后a=a+1是为了第二遍遍历的时候 tn=telnetlib.Telnet(host[a]) 能够登录到第二个ip地址。