【问题标题】:How to prevent pexpect from echoing the password?如何防止 pexpect 回显密码?
【发布时间】:2016-03-22 02:40:54
【问题描述】:

默认情况下,pexpect.spawn() 不会输出任何内容。但是当我指定logfile=sys.stdout 时,它也会回显密码(例如ssh)。那么如何在不回显密码的情况下查看与spawned 进程的实时交互(就像ExpectTcl 扩展名)一样)?

例子:

# 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


【解决方案1】:

只是为了回答问题。功劳归Thomas K。有关详细信息,请参阅问题下方的他的 cmets。

[STEP 101] # cat foo.py
#!/usr/bin/env python3

import pexpect, sys

spawn = pexpect.spawnu if sys.version_info[0] >= 3 else pexpect.spawn
ssh = spawn('ssh -t foo@localhost bash --noprofile --norc')
ssh.logfile_read = sys.stdout

ssh.expect('assword:')
ssh.sendline('123456')

ssh.expect('bash-[.0-9]+[$#]')
ssh.sendline('exit')
ssh.expect(pexpect.EOF)
ssh.wait()
[STEP 102] #
[STEP 103] # python2 foo.py
foo@localhost's password:
bash-5.1$ exit
exit
Connection to localhost closed.
[STEP 104] #
[STEP 105] # python3 foo.py
foo@localhost's password:
bash-5.1$ exit
exit
Connection to localhost closed.
[STEP 106] #

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2020-01-07
    • 1970-01-01
    • 2018-10-23
    • 2013-05-12
    相关资源
    最近更新 更多