【发布时间】:2016-03-22 02:40:54
【问题描述】:
默认情况下,pexpect.spawn() 不会输出任何内容。但是当我指定logfile=sys.stdout 时,它也会回显密码(例如ssh)。那么如何在不回显密码的情况下查看与spawned 进程的实时交互(就像Expect(Tcl 扩展名)一样)?
例子:
# cat expect.py
import pexpect, sys
logfile = sys.stdout if len(sys.argv) == 2 else None
ssh = pexpect.spawn('ssh foo@localhost', logfile=logfile)
ssh.delaybeforesend = 1
ssh.expect('assword:')
ssh.sendline('123456')
ssh.expect('\r\n\\$')
ssh.sendline('exit')
ssh.expect(pexpect.EOF)
ssh.wait()
# python expect.py <-- no output
# python expect.py stdout
foo@localhost's password: 123456 <-- the password is visible
Last login: Tue Mar 22 10:32:49 2016 from localhost
$ exit
exit
Connection to localhost closed.
#
预期示例:
# cat ssh.exp
spawn ssh foo@localhost
expect assword:
send "123456\r"
expect {\$}
send "exit\r"
expect eof
wait
# expect ssh.exp
spawn ssh foo@localhost
foo@localhost's password: <-- the password is invisible
Last login: Tue Mar 22 10:45:03 2016 from localhost
$ exit
Connection to localhost closed.
#
【问题讨论】:
-
刚刚尝试过,但它对我不起作用。还将它添加到我的示例代码中。
-
logfile记录双向的事情。您可以使用logfile_read仅捕获它从子进程读取的内容,而不是您发送的内容。这不是构造函数参数,但您可以在创建后设置ssh.logfile_read。 -
@ThomasK - 谢谢。这是部分解决方案。大多数时候,我想记录命令和命令的输出。但是你提醒我一个解决方法:在发送密码之前使用
logfile_read,在发送密码之后使用logfile。 -
Pexpect 看不到密码和命令之间的区别 - 它只是向 pty 发送一些字节。但是,通常当您发送命令时,pty 会将其回显给您(这是您在终端中键入时看到的方式)。这对密码关闭,因此您看不到它们。所以
logfile_read通常会包含命令。
标签: python-2.x expect pexpect