Python如何从pexpect child读取输出?

2024-06-28 19:18:13 发布

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

child = pexpect.spawn ('/bin/bash')
child.sendline('ls')
print(child.readline())
print child.before, child.after

我输出的这些代码

ls

ls 

但当我的密码是

child = pexpect.spawn('ls')
print(child.readline())
print child.before, child.after

然后就可以了,但只对前两张照片有效。我用错发送命令了吗?我试着发,写,发,再也找不到了。


Tags: 代码命令bashchild密码readlinebinls
3条回答
#!/usr/bin/env python

import pexpect
child = pexpect.spawn("ssh root@172.16.0.120c -p 2222")
child.logfile = open("/tmp/mylog", "w")
child.expect(".*assword:")
child.send("XXXXXXX\r")
child.expect(".*\$ ")
child.sendline("ls\r")
child.expect(".*\$ ")

打开日志文件:- 前往终点站

$gedit /tmp/mylog

在pexpect中,beforeafter属性在expect方法之后填充。在这种情况下,最常用的方法是等待提示(这样您就知道前面的命令已经完成执行)。所以,在你的例子中,代码可能看起来像这样:

child = pexpect.spawn ('/bin/bash')
child.expect("Your bash prompt here")
child.sendline('ls')
#If you are using pxssh you can use this
#child.prompt()
child.expect("Your bash prompt here")
print(child.before)

请尝试以下操作:

import pexpect
child = pexpect.spawn('ls')
print child.read() # not readline

read()将为您提供ls的整个输出。

相关问题 更多 >