Skip to content

Instantly share code, notes, and snippets.

@zhangzhhz
Created August 31, 2020 11:18
Show Gist options
  • Save zhangzhhz/4b5964a16ac6f077132c6a6001d1a332 to your computer and use it in GitHub Desktop.
Save zhangzhhz/4b5964a16ac6f077132c6a6001d1a332 to your computer and use it in GitHub Desktop.
Get issuer, subject and dates for all certs in a single cert file
#!/usr/bin/env python3
import os
import sys
import subprocess
import tempfile
f = 'mycerts.pem' if len(sys.argv) == 1 else sys.argv[1]
if os.path.exists(f) and os.path.isfile(f):
pass
else:
sys.exit(f'File [{f}] not found.')
start_line = '-----BEGIN CERTIFICATE-----'
end_line = '-----END CERTIFICATE-----'
start_line_key = '-----BEGIN PRIVATE KEY-----'
end_line_key = '-----END PRIVATE KEY-----'
files = []
in_key = False
in_cert = False
with open(f) as infile:
file_name_prefix = 'cert_'
seq_no = 0
outfile = None
for line in infile:
if start_line in line:
in_cert = True
seq_no += 1
# file_name = f'{file_name_prefix}{seq_no:02d}'
fd, file_name = tempfile.mkstemp(text=True)
outfile = open(fd, 'w')
outfile.write(line)
files.append(file_name)
elif end_line in line:
outfile.write(line)
outfile.close()
in_cert = False
elif start_line_key in line:
in_key = True
# file_name = f'key_01'
fd, file_name = tempfile.mkstemp(text=True)
outfile = open(fd, 'w')
outfile.write(line)
# files.append(file_name) # do not track key file
elif end_line_key in line:
outfile.write(line)
outfile.close()
in_key = False
elif in_cert or in_key:
outfile.write(line)
# if not outfile.closed:
# outfile.close()
# print(files)
cert_type = ''
for idx,f in enumerate(files):
if idx == 0:
cert_type = 'server cert'
elif idx == len(files) - 1:
cert_type = 'Root CA cert'
else:
cert_type = f'Intermediate CA cert {len(files) - idx - 1}'
print()
print(f'***** {cert_type} *****')
cmd = f'openssl x509 -noout -issuer -subject -dates -in {f}'
call_array = cmd.split()
# print(call_array)
resp = subprocess.run(call_array, text=True, capture_output=True)
if resp and resp.returncode == 0:
print(f'{resp.stdout.rstrip()}')
else:
print(f"Error getting cert information on [{f}]: [{resp.returncode}] {resp.stderr}")
# deleted cert files
os.remove(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment