我正在尝试使用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,我尝试了所有这些,但它对我不起作用。不知道怎样才能解决问题?
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 ...
。但是,如链接中所述,请确保您了解安全问题,以确保它不是您的用例的问题。