无法使用子进程[python]为进程提供密码

时间:2014-08-07 18:15:25

标签: python subprocess

我正在使用子进程从python中运行脚本。我试过这个

选项1

password = getpass.getpass()
from subprocess import Popen, PIPE, check_call  
proc=Popen([command, option1, option2, etc...], stdin=PIPE, stdout=PIPE, stderr=PIPE)  
proc.stdin.write(password)  
proc.stdin.flush()  
stdout,stderr = proc.communicate()  
print stdout  
print stderr  

和这个

选项2

password = getpass.getpass()
subprocess.call([command, option1, option2, etc..., password])

它们都不起作用,也就是说,密码不会发送到进程。如果我使用选项2并且不提供密码,则子流程会向我询问它并且有效。

2 个答案:

答案 0 :(得分:3)

以下是如何使用pexpect的基本示例:

import sys
import pexpect
import getpass

password = getpass.getpass("Enter password:")

child = pexpect.spawn('ssh -l root 10.x.x.x "ls /"')
i = child.expect([pexpect.TIMEOUT, "password:"])
if i == 0:
    print("Got unexpected output: %s %s" % (child.before, child.after))
    sys.exit()
else:
    child.sendline(password)
print(child.read())

输出:

Enter password:

bin
boot
dev
etc
export
home
initrd.img
initrd.img.old
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
selinux
srv
sys
tmp
usr
var
vmlinuz
vmlinuz.old

有更详细的例子here

答案 1 :(得分:0)

您应该将密码作为值传递给communicate()函数而不是stdin.write(),就像这样:

from getpass import getpass
from subprocess import Popen, PIPE

password = getpass("Please enter your password: ")
proc = Popen("command option1 option2".split(), stdin=PIPE, stdout=PIPE)
# Popen only accepts byte-arrays so you must encode the string
proc.communicate(password.encode())