无法通过subprocess提供密码给进程[python]

2 投票
2 回答
9657 浏览
提问于 2025-04-18 16:26

我在用Python里的subprocess模块来运行一个脚本。我试过这个

选项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但不提供密码,subprocess会问我要密码,这样一切就正常了。

2 个回答

1

你应该把密码作为一个值传递给 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())
5

这里有一个非常简单的例子,教你怎么使用 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

如果你想要更详细的例子,可以在 这里 找到。

撰写回答