0

您好我在 Python 中使用 pexpect 来读取 ssh 设备信息。

expObject = pexpect.spawn('/usr/bin/ssh %s@%s' % (username, device))
expObject.sendline(password)

输入密码后,我显示了一些设备信息,在命令提示符下它会要求按任意键继续;一旦我按下任何键,信息就会消失。

我使用以下逻辑来捕获发出命令后的其他数据show version

    expObject.expect(CLI_PROMPT)
    data = expObject.before

那么如何捕获在输入密码后和按任意键继续使用“expObject”之前显示的数据。

4

2 回答 2

2

我有一个类似的问题,我需要逐行处理文本输出。要使其正常工作,您必须知道 pexpect 配置正则表达式使得 .* 模式包含换行符,因此您必须使用 [^\n]* 而不是 .* 。这样的事情应该适用于您的情况:

child = pexpect.spawn('ssh command goes here')
child.expect('password prompt text\r\n')
child.sendline(password)
data = ""
while True:
    i = child.expect(['press any key to continue', '[^\n]*\r\n'])
    if i == 0:
        break
    data += child.before
print data

这应该与输出以下内容的命令一起使用:

password propt text
<start of data captured> - 1st line
a second line
a third line
last line <end of data that will be captured>
press any key to continue
于 2012-03-19T22:33:34.760 回答
1

http://ubuntuforums.org/showthread.php?t=220139

是您想要做什么的绝佳指南。我怀疑您实际上不需要使用 expect 并且只需执行 ssh 命令和 ssh 密钥就可以完成您想要的一切。例如:

hostA:~ jdizzle$ ssh hostB hostname
hostB

这是关于 ssh 密钥的另一个教程:http: //pkeck.myweb.uga.edu/ssh/

于 2012-02-26T05:01:34.690 回答