这个问题在这里已有答案:
我在终端中一个接一个地使用这三个Linux命令,以便在Raspberry Pi 3上启用监控模式。
iw phy phy0 interface add mon0 type monitor
ifconfig mon0 up
airudump-ng -w mon0
我想在Python文件而不是终端上运行这些命令。
我对子进程模块一无所知,但不知道如何做到这一点。
请建议我这样做的方法。
代码是
import subprocess
subprocess.call(["iw", "phy", "phy0", "interface", "add", "mon0", "type", "monitor"])
subprocess.call(["ifconfig", "mon0", "up"])
subprocess.call(["airodump-ng", "-w", "mon0"])
要么
import subprocess
subprocess.run(["iw", "phy", "phy0", "interface", "add", "mon0", "type", "monitor"])
subprocess.run(["ifconfig", "mon0", "up"])
subprocess.run(["airodump-ng", "-w", "mon0"])
如果你想使用标准输出/错误,建议使用后者by the docs。
下次,也许检查一下similar answer already exists。
将命令作为列表传递给subprocess.Popen
import subprocess
subprocess.Popen(["iw", "phy", "phy0", "interface", "add", "mon0", "type", "monitor"])
subprocess.Popen(["ifconfig", "mon0", "up"])
subprocess.Popen(["airudump-ng", "-w", "mon0"])
如果您需要等待命令完成使用.wait
或使用subprocess.call
编辑:如果需要读取stdout,stderr和退出状态,可以将它们传递给子进程。
p = subprocess.Popen([some cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout,stderr = p.communicate()
exit_status = p.wait()
使用终端上的vi编辑器创建和编辑脚本文件。根据需要,编辑器打开以编辑以下命令中的类型。
我们script.sh
iw phy phy0 interface add mon0 type monitor
ifconfig mon0 up
airudump-ng -w mon0
通过按键盘上的esc-> w-> q保存文件。
现在,如果您的脚本文件的路径可以说是/home/user/script.sh,在python代码中:
import subprocess
subprocess.call(["sh", "/home/user/script.sh"])