直接拼接字符串传给subprocess.run极危险,因shell=true时用户输入可触发shell注入;应禁用shell=true,改用参数列表如["ls", "-l"],需shell特性时严格隔离并shlex.quote()动态部分。

为什么直接拼接字符串传给 subprocess.run 很危险
因为 shell 注入风险真实存在:只要用户输入或外部数据参与了命令拼接,shell=True 下就可能执行任意命令。比如 subprocess.run(f"ls {user_input}", shell=True),当 user_input 是 "; rm -rf /" 时,后果严重。
安全的核心原则是——避免 shell=True,改用参数列表形式,让 Python 直接调用 exec 系统调用,跳过 shell 解析环节。
- 永远优先用
subprocess.run(["ls", "-l", "/tmp"]),而不是subprocess.run("ls -l /tmp", shell=True) - 如果必须用
shell=True(例如需要管道、通配符、重定向),确保命令字符串完全由你控制,且不含任何外部输入 - 绝对不要对不可信输入做
.format()或f""拼接后再传给shell=True
如何正确传递含空格或特殊字符的参数
用参数列表时,每个参数单独作为一个字符串元素,subprocess 会原样传递给子进程,不经过 shell 分词。这比手动转义可靠得多。
比如要执行 grep "hello world" /var/log/syslog:
subprocess.run(["grep", "hello world", "/var/log/syslog"])
注意:"hello world" 是一个完整参数,不会被拆开;而如果写成 ["grep", "hello", "world", ...],grep 就会误以为你要搜两个独立关键词。
仅使用 Python 将 Claw Code 虚拟化框架与 OpenClaw 集成,提供 184 种工具和 200 多条命令,用于安全分析和代码质量...
- 路径含空格?直接写
["cp", "/path/with space/file.txt", "/dest/"],不用加引号 - 需要变量插值?先赋值给变量,再放进列表:
filename = user_provided_path; subprocess.run(["cat", filename]) - 不确定参数是否安全?用
shlex.quote()处理单个字符串(仅限shell=True场景)
捕获输出和判断错误的推荐写法
默认情况下 subprocess.run 不捕获输出,出错也不抛异常,容易掩盖问题。
实际使用中应显式指定 capture_output=True 和 check=True:
result = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
capture_output=True,
text=True,
check=True
)
commit = result.stdout.strip()
-
capture_output=True等价于stdout=subprocess.PIPE, stderr=subprocess.PIPE -
text=True让stdout返回str而非bytes,避免后续手动.decode() -
check=True在返回码非 0 时自动抛subprocess.CalledProcessError,防止静默失败 - 如果需要区分 stdout/stderr,或允许某些非零码(如
grep找不到时返回 1),就别用check=True,改查result.returncode
哪些场景仍需 shell=True?怎么尽量减小风险
真正绕不开 shell=True 的情况不多,常见于:管道(|)、文件重定向(> file)、通配符展开(*.py)、环境变量引用($HOME)。
如果必须用,唯一可控方式是把动态部分严格隔离,并用 shlex.quote() 包裹:
import shlex
user_file = input("Enter filename: ")
cmd = f"cat {shlex.quote(user_file)} | head -n 5"
subprocess.run(cmd, shell=True, check=True)
-
shlex.quote()保证字符串在 shell 中被当作单个参数,但只适用于单个值,不能用于整个命令模板 - 像
find /tmp -name "*.log" | grep error这种复合命令,若涉及用户输入,优先考虑用 Python 原生实现(如pathlib+re),而非塞进 shell - Windows 上
shell=True调用的是cmd.exe,行为和 bash 差异大,跨平台脚本尽量避免
最易被忽略的一点:即使你没写 shell=True,如果传入的是单个字符串(如 subprocess.run("ls -l")),Python 会隐式启用 shell —— 这种写法等同于 shell=True,务必改成列表形式。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










