cert2json.py 1.86 KiB
#!/usr/bin/env python3
#
"""Certbot list 2 json
Usage:
cert2json.py --provider <PROVIDER>
cert2json.py (-h | --help)
Options:
-h --help Show this screen.
-p PROVIDER --provider=PROVIDER Provider [sectigo_ev | sectigo_ov | letsencrypt]
"""
import json
import re
import sys
import subprocess as sp
import yaml
from docopt import docopt
ARGS = docopt(__doc__)
PROVIDER = ARGS['--provider']
if PROVIDER not in ["letsencrypt", "sectigo_ov", "sectigo_ev"]:
print("valid providers are: sectigo_ev, sectigo_ov and letsencrypt")
sys.exit()
CMD = '/usr/local/bin/certbot certificates -c /etc/{}/cli.ini'.format(PROVIDER)
CBOT_CHILD = sp.Popen(CMD, stdout=sp.PIPE, stderr=sp.PIPE, shell=True)
CBOT_OUT, _ = CBOT_CHILD.communicate()
DECODED_OUTPUT = CBOT_OUT.decode("utf-8").split("\n")
TXT_FILE = "/var/www/acme_web/{}.txt".format(PROVIDER)
YAML_FILE = "/var/www/acme_web/{}.yaml".format(PROVIDER)
JSON_FILE = "/var/www/acme_web/{}.json".format(PROVIDER)
with open(YAML_FILE, "w") as yaml_out:
yaml_out.write("---\n")
for txt_line in DECODED_OUTPUT:
if "Certificate Name:" in txt_line:
txt_line_out = re.sub('.*Certificate Name: ', '- certname: ', txt_line)
elif "Serial Number: " in txt_line:
txt_line_out = re.sub('.*Serial Number: ', ' serial_number: ', txt_line)
elif "Domains: " in txt_line:
txt_line_out = re.sub('.*Domains: ', ' domains: "', txt_line) + '"'
elif "Expiry Date: " in txt_line:
txt_line_out = re.sub('.*Expiry Date: ', ' expiry_date: "', txt_line) + '"'
else:
txt_line_out = None
if txt_line_out:
yaml_out.write("{}\n".format(txt_line_out))
yaml_out.close()
with open(YAML_FILE, 'r') as yaml_in, open(JSON_FILE, "w") as json_out:
YAML_OBJECT = yaml.safe_load(yaml_in)
json.dump(YAML_OBJECT, json_out, indent=2)