如何在 python 中捕获 openssl 的输出

How to capture the output of openssl in python

我正在尝试 运行 python 中的以下 openssl 命令:

cmd = "openssl x509 -sha1 -in esx.crt -noout -fingerprint"
tmp = os.popen(cmd)
tmp_sha1 = tmp.readline()

此命令应该生成证书的指纹。我试图通过文件对象捕获输出。但是当我读取这个文件对象时,里面什么也没有。我已经在命令行上执行了这个命令,它 运行 很好,生成了指纹。你能告诉我如何获取指纹吗?

您可以使用两个模块来建立您想要的内容:subprocessos

使用 subprocess,您可以使用 communicate() 检查进程的输出,reads data from stdout and stderr until EOF

>>> import subprocess
>>> p = subprocess.Popen("openssl x509 -sha1 -in 17.cert -noout -fingerprint", stdout=subprocess.PIPE)
>>> out, _ = p.communicate() #return a tuple (stdout, stderr)
>>> out
b'SHA1 Fingerprint=87:68:8B:B0:6A:E2:DF:A3:E2:63:76:97:A9:2B:B4:F4:82:4E:0B:D1\n'

使用 os 模块也能正常工作,同时使用 read()readline() 方法:(请注意 os.popen() is deprecated

>>> import os
>>> p = os.popen("openssl x509 -sha1 -in 17.cert -noout -fingerprint")
>>> p.read()
'SHA1 Fingerprint=87:68:8B:B0:6A:E2:DF:A3:E2:63:76:97:A9:2B:B4:F4:82:4E:0B:D1\n'
>>> p = os.popen("openssl x509 -sha1 -in 17.cert -noout -fingerprint")
>>> out = p.readline()
'SHA1 Fingerprint=87:68:8B:B0:6A:E2:DF:A3:E2:63:76:97:A9:2B:B4:F4:82:4E:0B:D1\n'

如果您想将值写入文件,也可以,您可以通过在当前工作目录中打开文件 output.txt 来验证:

>>> with open('./output.txt', 'w') as f:
...     f.write(out)
...
77

77 通知我们已将 77 个字节写入文件,您可以通过在您喜欢的文本编辑器中打开它来验证。

您可以使用 OpenSSL 模块在 Python 中以本机方式实现此目的。

from OpenSSL.crypto import load_certificate, FILETYPE_PEM

cert_file_string = open("esx.crt", "rb").read()
cert = load_certificate(FILETYPE_PEM, cert_file_string)

sha1_fingerprint = cert.digest("sha1")
print sha1_fingerprint