我正在尝试telnet(使用控制台服务器的控制台)到Cisco路由器,运行一些show命令,并将它们的输出存储在变量中。
以下简单的脚本工作 - 在运行脚本之前已经登录到路由器(在现实世界的用例中不是很有用)
import telnetlib
import datetime
import getpass
import sys
import re
import time
import pexpect
host1_ip = "192.168.6.131"
host1_port = "32772"
user ="cisco"
password = "cisco123"
tn=pexpect.spawn("telnet " + host1_ip + " " + host1_port, maxread=16384)
tn.sendline("show ip interface brief")
time.sleep(5)
tn.expect("CE1#")
data1=tn.before
print(data1.decode('utf-8'))
输出是(data1' s内容):
show ip interface brief
Interface IP-Address OK? Method Status Protocol
Ethernet0/0 unassigned YES NVRAM administratively down down
Ethernet0/1 unassigned YES NVRAM administratively down down
Ethernet0/2 unassigned YES NVRAM administratively down down
Ethernet0/3 unassigned YES NVRAM administratively down down
Serial1/0 unassigned YES NVRAM administratively down down
Serial1/1 unassigned YES NVRAM administratively down down
Serial1/2 unassigned YES NVRAM administratively down down
Serial1/3 unassigned YES NVRAM administratively down down
期待" CE1#"因为这是" CE1#"
的第一次出现但是,当我使用更有用的脚本登录到路由器,配置它,然后获取/存储show命令的输出时,它不起作用。
import telnetlib
import datetime
import getpass
import sys
import re
import time
import pexpect
host1_ip = "192.168.6.131"
host1_port = "32772"
user ="cisco"
password = "cisco123"
tn=pexpect.spawn("telnet " + host1_ip + " " + host1_port, maxread=16384)
tn.send("\r")
tn.expect("Username: ")
tn.sendline(user)
tn.expect("Password: ")
tn.sendline(password)
tn.sendline("terminal length 0")
tn.sendline("terminal width 0")
time.sleep(5)
tn.expect("CE1#")
tn.sendeof
tn.sendline("show ip interface brief")
time.sleep(5)
tn.expect("CE1#")
data1=tn.before
print(data1.decode('utf-8'))
tn.sendline("exit")
输出是:
terminal length 0
期待" CE1#"在" show ip interface brief"不起作用,因为" CE1#"以前遇到过很多。
当我登录路由器时," CE1#"看到了。 当我配置"终端长度0","终端宽度0"时,看到CE1#
Username: cisco
Password:
CE1#terminal length 0
CE1#terminal width 0
如何清除缓冲区,以便以前遇到过" CE1#"被删除? 尝试过(1)添加'期望" CE1#"之前的陈述(理想情况下,child.before只应该在最后期望之后读出输出' (2)发送eof(3)使用child.flush等发送flush。 他们都没有帮助。