Search code examples
pythonopenssl

How to capture the output of openssl in python


I am trying to run the following openssl command in python:

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

This command is supposed to generate a fingerprint of the certificate. I am trying to capture the output through the file object. But when I read this file object, there's nothing in it. I have executed this command on the command line and it runs fine, generates the fingerprint. Could you tell me how can I get the fingerprint?


Solution

  • You achieve this natively within Python using the OpenSSL module.

    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