You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原含命令注入风险的Python代码改写后,是否已修复安全问题?

问题修复确认

是的,你已经成功修复了恶意代码执行的安全风险。

原代码的风险点

原代码使用os.system()执行拼接后的字符串命令:

import os

command = "conda run -n python3.5 python generate_handwriting.py -text '{}' -style {} -bias {} -stroke_color '{}' -stroke_width {} -output '{}'".format(text, style, bias, stroke_color, stroke_width, output_filename)
os.system(command)

这种字符串拼接的方式依赖系统shell解析命令,当用户输入包含shell特殊字符(比如'; rm -rf / #)时,会被解析成额外的恶意命令。例如如果用户在text参数中输入'$(rm -rf /)',shell会优先执行括号内的删除操作,造成严重破坏。

改写后代码的安全性

改写后的代码使用subprocess.run()的列表参数形式:

import subprocess

cmd = ["conda", "run", "-n", "python3.5", "python", "generate_handwriting.py"]
args = ["-text", str(text), "-style", str(style), "-bias", str(bias), "-stroke_color", str(stroke_color), "-stroke_width", str(stroke_width), "-output", output_filename]

process = subprocess.run(cmd + args, check=True)

这种方式不会通过shell解析命令,而是直接将列表中的每个元素作为程序的参数传递。用户输入的任何特殊字符都会被当作普通字符串处理,不会被解释为shell命令的一部分,从根源上避免了命令注入的风险。

另外,check=True的设置会在子进程执行失败时主动抛出异常,便于后续的错误处理,是值得保留的良好实践。

内容的提问来源于stack exchange,提问作者SlimiBoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 13:23:10