Python 如何在子进程支持的sudo命令中输入密码?

Python 如何在子进程支持的sudo命令中输入密码?,python,subprocess,Python,Subprocess,我试图用python子进程库运行这个命令,我的目标是创建脚本。当我运行这个命令时,脚本将从文件中读取密码,并将其添加到子进程中,然后执行该命令。问题是我总是要写密码来执行命令 我试过这个,但对我不起作用 p = subprocess.Popen(["sudo", "nmap", "-sP", "-n", network], stdin=subprocess.PIPE, stdout=subprocess.PIPE) p.stdin.write(bytes("Mypassword", "utf-8

我试图用python子进程库运行这个命令,我的目标是创建脚本。当我运行这个命令时,脚本将从文件中读取密码,并将其添加到子进程中,然后执行该命令。问题是我总是要写密码来执行命令

我试过这个,但对我不起作用

p = subprocess.Popen(["sudo", "nmap", "-sP", "-n", network], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write(bytes("Mypassword", "utf-8"))

我在这里找到了一些解决方案,我尝试了所有的方法,但都不适用于我。知道如何解决问题吗?

sudo手册页指定:

 -S, --stdin
             Write the prompt to the standard error and read the password from the stan‐
             dard input instead of using the terminal device.  The password must be fol‐
             lowed by a newline character.
运行以下代码可以解决您的问题:

p = subprocess.Popen(["sudo", "-S", "cmd"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write("password\n")
显然,请确保您提供了正确的密码,否则这将无法工作。另外,不要忘记在末尾添加
\n


作为替代方案,您可以运行。这将允许您使用不需要密码的
nmap--privileged…
。不过,正如链接中所述,请确保您了解安全问题,以确保它不是您的用例的问题。

可能重复@OlvinRoght,我也尝试过这一点。