如何解析shell重定向和管道命令以使用shell = False来子处理popen命令[关闭]

问题描述 投票:0回答:1

我有一个python脚本,它将shell命令作为输入(command),然后使用]调用相同的脚本>

subprocess.Popen(command, shell=True)

这很好。但是,我意识到选项shell=True导致命令行注入漏洞。因此,我想将代码更改为shell=False。我写了类似的东西:

import subprocess
import shlex

def parse_command(command):
    parsed_command = shlex.split(command)
    # Some more parsing
    return parsed_command

command = raw_input("Enter the command: ")
parsed_command = parse_command(command)
subprocess.Popen(parsed_command) # By default shell=False

但是,我的parse_command不足以进行重定向(>,>>,2>&1等)或管道(|)。例如,如果我直接在终端中键入命令,则会看到以下结果:

〜#echo“ hi”> output.txt

〜#cat output.txt

hi

但是,我的python脚本给出了错误的结果:

〜#python my_parser.py

[输入命令:

echo“ hi”> output.txt

hi> output.txt

因此,有人可以建议我如何解析包含重定向和管道选项的shell命令,以便可以在带有shell=False的子进程popen命令中使用它。

谢谢。

我有一个python脚本,它将shell命令作为输入(命令),然后使用subprocess.Popen(command,shell = True)调用它。但是,我意识到选项shell = ...

python shell redirect subprocess
1个回答
0
投票

我认为,如果在单独的Shell脚本中传递命令并通过subprocess模块​​运行该Shell脚本会更好。可执行的shell脚本可以是这样的:

© www.soinside.com 2019 - 2024. All rights reserved.