输入密码时,Python 子进程模块无法重定向标准输出?

标签 python linux

我想与子进程终端交互并发送密码,但我注意到如果某些程序调用 getpass(prompt)( http://www.gnu.org/savannah-checkouts/gnu/libc/manual/html_node/getpass.html )

这意味着我无法与sudossh 交互,那么如何解决这个问题呢?谢谢。

例子如下:

process = subprocess.Popen(['sudo', 'apt', 'update'],
                       bufsize=0,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       stdin=subprocess.PIPE)
while True:
    # prefix '>>' in parent process
    # but we could see the stdout without prefix, that means read() never return
    # the subprocess just ignored the redirect of stdout
    print('>>', process.stdout.read())
    time.sleep(1)

最佳答案

你的问题不清楚,不过我会尽量回答

如果要发送密码,可以使用communicate()方法

关于 communicate() 的更多信息在这里 Multiple inputs and outputs in python subprocess communicate

所以你的代码应该是这样的

from subprocess import Popen,PIPE
proc = Popen(['sudo', 'apt', 'update'],
                       bufsize=0,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       stdin=subprocess.PIPE)

testoutput=proc.communicate(input='your password')[0] # This will enter the password and wait for the process to exit
print ''.join(testoutput)

关于输入密码时,Python 子进程模块无法重定向标准输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47990982/

相关文章:

python - CherryPy url 编码问题

python - django taggit防止不同模型之间的重叠标签

linux - 如何在一个文件中运行多个命令

c - RAM 内存中的段

linux - JBoss 7 中的 UDP 连接在哪里配置?

linux - 在 bash 中转换日期格式

python - 如何在 python 中使用 ecdsa 签名和验证签名

python - Selenium ElementNotVisibleException : Message: element not interactable

python - 如何使 PyQt 中的菜单项变灰

c++ - 线程安全的 vector 和字符串容器?