Python-如何使用Popen获取Sudo命令的输出

问题描述

sudo命令根据用户名验证用户密码。我正在编写一个简单的程序,该程序根据sudo命令检查用户输入是否有效。我使用-S标记以将输入传递给外部,并且我使用Popen()运行脚本:

import getpass
import subprocess
import time

password = getpass.getpass()
proc = subprocess.Popen('sudo -k -S -l'.split(),stdin=subprocess.PIPE,stderr=subprocess.PIPE,stdout=subprocess.PIPE)
output = proc.communicate(password.encode())
print(f'This is the value of the output {output[0]}')

如果用户getpass.getpass()中输入了错误密码,则需要根据实际的用户密码进行验证。在这种情况下,sudo应该输出Sorry Please Try Again。有人可以让我知道如何读取该错误吗?

当我在终端中运行此程序时:

➜  Desktop python3.8 test.py
Password: 
Sorry,try again.
This is the value of the output b''

谢谢,欢呼,非常感谢您的帮助。

解决方法

Python Documentation说:

请注意,如果要将数据发送到流程的stdin,则需要使用stdin = PIPE创建Popen对象。

所以使用

proc = subprocess.Popen(['sudo','-S','-l'],stdin=subprocess.PIPE,stderr=subprocess.PIPE,stdout=subprocess.PIPE)

允许使用communicate编写密码,否则它只是等待您在终端上输入密码(由于被捕获,因此没有提示)。

output变量(特别是与标准错误对应的output[1])中有任何错误消息。