Pexpect没有等待整个输出Ubuntu

2024-04-16 10:35:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的脚本将SSH连接到网络交换机,运行命令并将输出保存到文件中。对于即时显示的输出,它工作得很好,但当我运行“showiproute”时,它不会捕获任何输出。原因是当我直接在switch上运行相同的命令时,它会思考5-6秒,显示一堆行,然后再思考,再显示几行,然后结束。我正在修复问题,但没有正确等待整个命令的执行:

str_prompt = ' # '
command = "sh iproute"
device_name = "switch1.test.com"

# Spawn SSH session
ssh_command = 'ssh {}@{}'.format(username, device_name)
session = pexpect.spawn(ssh_command, timeout=5)

# Send the password
session.sendline(password)

# Expect the switch prompt (successful login)
expect_index = session.expect([pexpect.TIMEOUT, str_prompt])
# Success
if expect_index == 1:
    # Disable clipaging so that all the output is shown (not in pages) | same as term len 0 in Cisco
    session.sendline('disable clip')
    # Expect the switch prompt if command is successful
    expect_index = session.expect([pexpect.TIMEOUT, str_prompt])

    # Send show iproute command
    session.sendline(command)
    # < This is where it needs to wait >
    #session.expect(pexpect.EOF) - Tried this and wait() but that broke the scipt
    #session.wait()
    # Expect the switch prompt if command is successful
    session.expect(str_prompt)

    # Save output of "sh iproute" to a variable
    output = session.before
    # Save results to a file
    fp = open(host + '-route.txt', "w")
    fp.write(output)
    fp.close()

下面是一个输出示例。输出确实有“#”,但没有“#”。在

^{pr2}$

任何帮助都将不胜感激。谢谢

编辑: 我添加了sleep(60),这似乎起到了作用,但我不想使用它,因为我正在发送多个命令,有些命令的速度非常快。我不想为每个命令等待1分钟,脚本将永远运行。在


Tags: the命令outputissessionsshpromptcommand
1条回答
网友
1楼 · 发布于 2024-04-16 10:35:12

所以需要将超时与命令关联起来。 我今天的方法是有一个xml文件格式,我的代码会解析它,xml标记将有一个用于命令的属性,另一个属性用于超时,另一个属性用于命令的结束提示,等等。。在

我的代码读取命令及其超时,并在发送命令之前相应地设置相应的变量。在

session.sendline(command) #command is read from a xml file
session.expect(end_prompt, timeout=int(tmout)) # end_prompt, tmout for the command read form the same file

对于您的情况,如果您不想解析一个文件来获取命令及其相关参数,您可以在脚本中将它们作为字典使用

^{pr2}$

字典内的cmd_details是一个字典列表,这样您可以在迭代时维护命令的顺序,每个命令都是一个包含相关详细信息的字典,您可以在命令字典中添加更多的键,例如提示、唯一标识符etcc。。在

但是如果你有时间,我建议你用一个配置文件代替

相关问题 更多 >