unable to provide password to a process with subpr

2019-01-29 03:39发布

问题:

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

option 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  

and this

option 2

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

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.

回答1:

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())

Output:

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

There are more detailed examples here.