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

如何使用Python subprocess获取openssl解密命令的执行输出?

从subprocess执行的OpenSSL解密操作中获取结果

当然可以,你有两种常用方式获取解密后的值:生成解密文件,或者直接将结果捕获到变量中,以下分别说明:

1. 生成解密文件(你的示例方式)

你当前的代码已经通过-out参数指定了解密后文件的路径,执行该命令后,OpenSSL会自动将解密内容写入到name变量指定的文件中。执行完成后,你可以直接读取这个文件获取解密值:

decryption_result = subprocess.run(['openssl', 'decrypt', '-inkey', private_key_file,'-in', message_file, '-out', name])
# 检查命令是否执行成功
if decryption_result.returncode == 0:
    # 读取解密后的文件内容(如果是二进制文件,将'r'改为'rb',去掉encoding参数)
    with open(name, 'r', encoding='utf-8') as f:
        decrypted_content = f.read()
else:
    # 处理解密失败的情况,比如打印错误信息
    print("解密失败,错误信息:", decryption_result.stderr)

2. 将解密结果直接捕获到变量中

如果不想生成中间文件,可以去掉-out参数,让OpenSSL将解密结果输出到标准输出(stdout),然后通过subprocess的参数捕获这个输出:

  • 如果解密内容是文本格式,使用capture_output=True和encoding参数直接获取字符串:
import subprocess

result = subprocess.run(
    ['openssl', 'decrypt', '-inkey', private_key_file, '-in', message_file],
    capture_output=True,
    encoding='utf-8'
)

if result.returncode == 0:
    decrypted_content = result.stdout
    # 直接使用decrypted_content变量即可
else:
    print("解密失败:", result.stderr)
  • 如果解密内容是二进制数据(如图片、压缩包等),不要指定encoding,直接获取字节数据:
import subprocess

result = subprocess.run(
    ['openssl', 'decrypt', '-inkey', private_key_file, '-in', message_file],
    capture_output=True
)

if result.returncode == 0:
    decrypted_bytes = result.stdout
    # 可以将字节数据写入文件或者直接处理
    with open('decrypted_binary.bin', 'wb') as f:
        f.write(decrypted_bytes)
else:
    print("解密失败:", result.stderr.decode('utf-8'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:20:15