如何将数据重定向到像密码输入这样的“getpass”?

时间:2011-01-28 09:41:52

标签: python passwords stdin getpasswd

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

input.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字段上。这是问题,为什么我不能将数据放到stdin来将数据提供给密码字段?如何将数据写入密码字段?

2 个答案:

答案 0 :(得分:2)

对于此类情况,您需要pexpect模块。

  

Pexpect是一个Python模块   产卵儿童应用和   自动控制它们。   Pexpect可用于自动化   交互式应用程序,如ssh,   ftp,passwd,telnet等

答案 1 :(得分: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,那么这是一种时髦的过时方法,可能会让事情变得混乱。