【发布时间】:2018-01-05 21:51:12
【问题描述】:
我有一个简单的脚本,可以通过 SSH 连接到网络交换机并运行命令并将输出保存到文件中。它适用于立即显示的输出,但是当我运行“show iproute”时,它不会捕获任何输出。原因是当我直接在交换机上运行相同的命令时,它会思考 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()
这是一个示例输出。输出确实有“#”但没有“#”。
#oa 10.10.10.0/24 10.0.0.1 4 UG-D---um--f- V-BB1 99d:0h:14m:49s
#oa 10.10.20.0/24 10.0.0.1 4 UG-D---um--f- V-BB2 99d:0h:14m:49s
#oa 10.10.30.0/24 10.0.0.1 4 UG-D---um--f- V-BB3 99d:0h:14m:49s
#oa 10.10.40.0/24 10.0.0.1 4 UG-D---um--f- V-BB4 99d:0h:14m:49s
and many more line ....
任何帮助将不胜感激。谢谢
编辑: 我添加了 sleep(60) ,这似乎可以解决问题,但我不想使用它,因为我正在发送多个命令,而且有些命令非常快。我不想为每个命令等待 1 分钟,脚本将永远运行。
【问题讨论】:
-
撞我的问题....
标签: python python-2.7 pexpect