如何将Python变量传递到shell命令中
解决方案
推荐写法(禁用shell=True,更安全)
这是最优方案,完全规避shell注入风险,也不需要额外处理特殊字符转义,直接把变量填充到参数列表即可:
import subprocess # 你已定义的三个变量 webhost = "你的主机地址" username = "你的账号" password = "你的密码" output = subprocess.check_output( [ "curl", "-s", "-G", "-u", f"{username}:{password}", "-k", f"https://{webhost}/something/something" ], encoding="utf-8" )
必须使用shell=True的写法
如果因特殊场景必须保留shell=True,可以用字符串格式化把变量拼接到命令中,若变量包含空格、&等shell特殊字符,建议用shlex.quote()做转义处理:
import subprocess import shlex webhost = "你的主机地址" username = "你的账号" password = "你的密码" cmd = f'curl -s -G -u {shlex.quote(username)}:{shlex.quote(password)} -k "https://{shlex.quote(webhost)}/something/something"' output = subprocess.check_output(cmd, shell=True, encoding="utf-8")
注意事项
- 除非你完全确认三个变量的取值都是可信的、不包含任何特殊控制字符,否则不要使用
shell=True的写法 - 两种写法都已经完成变量的动态传入,直接替换变量的测试值即可正常运行
内容的提问来源于stack exchange,提问作者Abhinandan Aithal
相关产品推荐
相关产品推荐

