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

2024-04-26 14:01:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python子进程库运行这个命令sudo nmap -sP -n,我的目标是创建脚本当我运行这个命令时,脚本将从一个文件中读取密码并将其添加到子进程并执行这个命令。问题是我总是要写密码来执行命令。你知道吗

我试过这个,但对我不起作用。你知道吗

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

我在这里找到了一些解决方案Use subprocess to send a password,我尝试了所有的方法,但都不适用于我。你知道我怎么解决这个问题吗?你知道吗


Tags: 文件命令脚本密码目标进程stdinsudo
1条回答
网友
1楼 · 发布于 2024-04-26 14:01:37

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 as an unprivileged user。这将允许您使用不需要密码的nmap privileged ...。但是,正如链接中所指定的,请确保您了解安全问题,以确保它不是您的用例的问题。你知道吗

相关问题 更多 >