Skip to content

Instantly share code, notes, and snippets.

@farhany
Created July 19, 2019 03:12
Show Gist options
  • Save farhany/7442f3e87eb1abc28dc3b792dc0fc2d9 to your computer and use it in GitHub Desktop.
Save farhany/7442f3e87eb1abc28dc3b792dc0fc2d9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import argparse
import base64
import json
import os
def main():
# parser = argparse.ArgumentParser(
# description="Dump all certificates out of Traefik's acme.json file")
# parser.add_argument('acme_json', help='path to the acme.json file')
# parser.add_argument('dest_dir',
# help='path to the directory to store the certificate')
# args = parser.parse_args()
# certs = read_certs(args.acme_json)
args = {'acme_json': './acme.json', 'dest_dir': 'ssl/'}
print(args)
certs = read_certs(args['acme_json'])
# return
print('Found certs for %d domains' % (len(certs),))
for domain, cert in certs.items():
print('Writing cert for domain %s' % (domain,))
write_cert(args['dest_dir'], domain, cert)
print('Done')
def read_cert(storage_dir, filename):
cert_path = os.path.join(storage_dir, filename)
if os.path.exists(cert_path):
with open(cert_path) as cert_file:
return cert_file.read()
return None
def write_cert(storage_dir, domain, cert_content):
cert_path = os.path.join(storage_dir, '%s.pem' % (domain,))
with open(cert_path, 'wb') as cert_file:
cert_file.write(cert_content)
os.chmod(cert_path, 0o600)
return
def read_certs(acme_json_path):
with open(acme_json_path) as acme_json_file:
acme_json = json.load(acme_json_file)
certs_json = acme_json['Certificates']
# print("-----dumping certs_json-----")
# print(certs_json)
# print("len: {}".format(len(certs_json)))
# print("domain_main: {}".format(certs_json[0]['Domain']['Main']))
certs = {}
for cert in certs_json:
domain = cert['Domain']['Main']
# print(domain)
# print(cert['Certificate'])
# print(cert['Key'])
domain_cert = { 'Certificate': cert['Certificate'], 'Key': cert['Key'] }
# Only get the first cert (should be the most recent)
if domain not in certs:
print("domain: {}".format(domain))
certs[domain] = to_pem_data(domain_cert)
return certs
def to_pem_data(json_cert):
return b''.join((base64.b64decode(json_cert['Certificate']),
base64.b64decode(json_cert['Key'])))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment