通过 python 中的子进程运行 bash-command,没有强盗警告 B404 和 B603

And*_* L. 5 python bash subprocess bandit-python

由于预提交挂钩甚至不允许bandit发出警告和提交,因此我需要找到一种方法从 python 脚本执行 bash 命令,而不会有 bandit 抱怨。

bandit-lintings

使用subprocess python 包,到目前为止,无论我做了什么,强盗总是抱怨。我使用了“.run()”、“.check_call()”、“.Popen()”等,但都没有使用,shell=True但没有任何效果。

如果有一个安全的子流程替代方案,我也会感兴趣,但我确信它也必须以某种方式与子流程一起工作。


强盗不接受的示例:

import shlex
import subprocess

...

bash_command = (
    f'aws s3 cp {source_dir} s3://{target_bucket_name} --recursive'
    f' --profile {profile_name}')
subprocess.check_call(shlex.split(bash_command), text=True)
Run Code Online (Sandbox Code Playgroud)

Car*_*lsh 1

为了使代码安全,您需要知道这些代码source_dir target_bucket_name profile_name不是恶意的:例如,不受信任的用户可以.ssh作为要复制的值传递吗?

一旦您知道子流程线是安全的,您可以添加# nosec注释来告诉 bandit 不要发出有关该线的警告:

subprocess.check_call(shlex.split(bash_command), text=True)  # nosec
Run Code Online (Sandbox Code Playgroud)

aws s3 ...(运行的命令subprocess.check_call不是在 bash shell 中运行,这可能会让阅读问题的人感到困惑。Python 将直接启动该aws进程,传递参数。)