【问题标题】:python3 pexpect how to flush buffer after expect(<string>)python3 pexpect如何在expect(<string>)之后刷新缓冲区
【发布时间】: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


【解决方案1】:

不太确定 3 年后这是否有用,但它就在这里:

在您的情况下,您需要按顺序执行 .sendline('something') .expect('something') 才能正确跟踪缓冲区。

在您的代码中,您期望的打印可能在缓冲区或 .after 中

无论如何,如果您想强制清除缓冲区,请使用:

 if my_child.before:
           
       my_child.expect(r'.+')

【讨论】:

    猜你喜欢
    • 2020-03-30
    • 2010-09-20
    • 1970-01-01
    • 2015-08-10
    • 2021-09-03
    • 2018-07-11
    • 1970-01-01
    • 2010-09-23
    相关资源
    最近更新 更多