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

2022-01-18 00:00:00 python subprocess

问题描述

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

I'm using subprocess to run a script from within python. I tried this

选项 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 并且不提供密码,则子进程会要求我提供密码并且一切正常.

Neither of them work, that is, the password is not sent to the process. If I use option 2 and do not provide password, the subprocess asks me for it and everething works.


解决方案

这是一个非常基本的使用示例期待:

Here's a very basic example of how to use pexpect for this:

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

有更详细的示例这里.

相关文章