【发布时间】:2018-06-07 01:43:47
【问题描述】:
我正在尝试远程登录(使用控制台服务器的控制台)到 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的内容):
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
在“show ip interface brief”之后期待“CE1#”不起作用,因为之前经常遇到“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 等发送刷新。 他们都没有帮助。
【问题讨论】:
-
顺便说一句,您甚至使用已导入的 telnetlib 吗?
-
这只是我之前尝试使用 telnetlib 的遗留物。我最终会删除它。谢谢
标签: python-3.x buffer pexpect