Python subprocess调用OpenSSL用<符号报错,如何实现字符串解密?
解决subprocess调用OpenSSL解密时的Shell语法错误问题
这个问题我碰到过!你遇到的Syntax error: "(" unexpected错误,根源在于默认情况下subprocess.Popen会用/bin/sh执行命令,而sh不支持bash特有的进程替换语法<(echo ...)。下面给你两个可行的解决办法:
方法一:指定用Bash执行命令
直接在Popen里指定executable='/bin/bash',让命令在bash环境下运行,这样就能支持<(...)语法了。修改后的代码如下:
from subprocess import Popen, PIPE cmd = 'openssl enc -aes-256-cbc -in <(echo U2FsdGVkX18SNFZ4AAAAAKJTAirWf4KnDHYXlIF/87Y=) ' \ '-d -a -k 12345678 -S 12345678 -iv 12345678' x = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, executable='/bin/bash') output, error = x.communicate() if error: print(f"错误信息: {error.decode()}") else: print(output.decode().strip())
方法二:通过标准输入传递加密字符串(更推荐)
其实没必要用进程替换,直接把加密字符串通过stdin传给openssl命令,这种方式更简洁,还能避免shell语法的兼容性问题。代码示例:
from subprocess import Popen, PIPE encrypted_str = "U2FsdGVkX18SNFZ4AAAAAKJTAirWf4KnDHYXlIF/87Y=" cmd = ['openssl', 'enc', '-aes-256-cbc', '-d', '-a', '-k', '12345678', '-S', '12345678', '-iv', '12345678'] x = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, error = x.communicate(input=encrypted_str.encode()) if error: print(f"错误信息: {error.decode()}") else: print(output.decode().strip())
这里把命令拆成列表形式(更安全,避免shell注入风险),然后通过communicate的input参数把加密字符串传给openssl的标准输入,完美替代进程替换的作用,还能跨不同shell环境运行。
内容的提问来源于stack exchange,提问作者Ñhosko
相关产品推荐
相关产品推荐

