如何在Python文件中运行多个Linux命令

时间:2019-03-23 11:45:51

标签: python linux subprocess python-3.6

我在终端中依次使用这三个Linux命令在Raspberry Pi 3上启用监视模式。

iw phy phy0 interface add mon0 type monitor

ifconfig mon0 up

airudump-ng -w mon0

我想在Python文件中而不是在终端上运行这些命令。

我对子流程模块一无所知,但不知道该怎么做。

请给我建议一种方法。

3 个答案:

答案 0 :(得分:0)

代码是

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

另请参阅this other answer

下次,也许检查一下similar answer already exists

答案 1 :(得分:0)

将命令作为列表传递到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()

答案 2 :(得分:0)

在终端上使用vi编辑器创建和编辑脚本文件。打开编辑器进行编辑后,根据需要键入以下命令。

  

vi script.sh

iw phy phy0 interface add mon0 type monitor

ifconfig mon0 up

airudump-ng -w mon0

通过按键盘上的esc-> w-> q保存文件。

现在,如果脚本文件的路径在python代码中为/home/user/script.sh,则为:

import subprocess
subprocess.call(["sh", "/home/user/script.sh"])
相关问题