6

我正在编写一个 python 脚本来运行一些命令。其中一些命令需要用户输入密码,我确实尝试在他们的标准输入中输入数据,但它不起作用,这里有两个简单的python程序代表问题

输入.py

import getpass

print raw_input('text1:')
print getpass.getpass('pass1:')
print getpass.getpass('pass2:')

put_data.py

import subprocess
import getpass

def run(cmd, input=None):
    stdin=None
    if input:
        stdin=subprocess.PIPE
    p = subprocess.Popen(cmd, shell=True, stdin=stdin)
    p.communicate(input)
    if p.returncode:
        raise Exception('Failed to run command %r' % cmd)

input ="""text1
password1
password2
"""
run('python test.py', input)

这是输出

[guest@host01 ~]# python put_data.py 
text1:text1
pass1:

它只是停在 pass1 字段上。这就是问题所在,为什么我不能将数据放入标准输入以将数据提供给密码字段?如何将数据写入密码字段?

4

2 回答 2

2

对于这种情况,您需要pexpect模块。

Pexpect 是一个 Python 模块,用于生成子应用程序并自动控制它们。Pexpect 可用于自动化交互式应用程序,例如 ssh、ftp、passwd、telnet 等。

于 2011-01-28T10:31:00.910 回答
0

绝对不需要两个班级来制作这样的东西。您需要做的就是在 put_data.py 中创建另一个名为init_ () 的方法,然后执行以下操作:

x = raw_input('text1:')
y = getpass.getpass('pass1:')
z = getpass.getpass('pass2:')

然后你可以使用 pexpect 来完成剩下的工作:

child = pexpect.spawn(x, timeout=180)
while True:
   x = child.expect(["(current)", "new", "changed", pexpect.EOF, pexpect.TIMEOUT])
   if x is 0:
      child.sendline(y)
      time.sleep(1)
   if x is 1:
      child.sendline(z)
      time.sleep(1)
   if x is 2:
      print "success!"
      break

多田!当然,您可能会在使用这样的代码时遇到大量错误。您应该始终使用提供的方法,如果您使用的是 linux,则运行 os.system("passwd") 并让 shell 处理其余部分可能会更容易。此外,如果可能的话,总是避免使用 getpass,这是一种时髦的过时方法,并且可能会在路上搞砸。

于 2011-09-19T16:23:29.613 回答