默认情况下,pexpect.spawn()
不会输出任何东西。但是当我指定logfile=sys.stdout
它还会回显密码(例如ssh
)。那么我怎样才能看到与spawn
ed 进程没有回显密码(就像Expect
(the 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.
#
只是为了让问题得到解答。功劳归于Thomas K。有关更多详细信息,请参阅问题下他的评论。
# cat foo.py
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()
# python2 foo.py
foo@localhost's password:
bash-5.1$ exit
exit
Connection to localhost closed.
# python3 foo.py
foo@localhost's password:
bash-5.1$ exit
exit
Connection to localhost closed.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)