无法使用子进程 [python] 向进程提供密码 [英] unable to provide password to a process with subprocess [python]

查看:17
本文介绍了无法使用子进程 [python] 向进程提供密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用子进程从 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

有更详细的示例这里.

这篇关于无法使用子进程 [python] 向进程提供密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆