【问题标题】:How to redirect data to a "getpass" like password input?如何将数据重定向到密码输入之类的“getpass”?
【发布时间】:2011-06-17 03:19:01
【问题描述】:

我正在编写一个 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 字段上。这是问题所在,为什么我不能将数据放入标准输入以将数据提供给密码字段?如何将数据写入密码字段?

【问题讨论】:

    标签: python passwords stdin getpasswd


    【解决方案1】:

    在这种情况下,您需要 pexpect 模块。

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

    【讨论】:

      【解决方案2】:

      绝对不需要两个班级来制作这样的东西。您需要做的就是在 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,这是一种过时的时髦方法,并且可能会在未来搞砸。

      【讨论】:

      • 我忘了提到,如果你确实使用 __init__() 方法,你将不得不创建 x、y 和 z 全局变量,否则它们不会传递到你的 run( ) 方法。
      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      相关资源
      最近更新 更多