python3 pexpect如何在expect之后刷新缓冲区(<string>)

时间:2017-12-26 06:36:07

标签: python-3.x buffer pexpect

我正在尝试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&#39; 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

期待&#34; CE1#&#34;因为这是&#34; CE1#&#34;

的第一次出现

但是,当我使用更有用的脚本登录到路由器,配置它,然后获取/存储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

期待&#34; CE1#&#34;在&#34; show ip interface brief&#34;不起作用,因为&#34; CE1#&#34;以前遇到过很多。

当我登录路由器时,&#34; CE1#&#34;看到了。 当我配置&#34;终端长度0&#34;,&#34;终端宽度0&#34;时,看到CE1#

Username: cisco
Password:
CE1#terminal length 0
CE1#terminal width 0

如何清除缓冲区,以便以前遇到过&#34; CE1#&#34;被删除? 尝试过(1)添加&#39;期望&#34; CE1#&#34;之前的陈述(理想情况下,child.before只应该在最后期望之后读出输出&#39; (2)发送eof(3)使用child.flush等发送flush。 他们都没有帮助。

0 个答案:

没有答案