Skip to content

Instantly share code, notes, and snippets.

@lukecampbell
Created August 14, 2019 15:26
Show Gist options
  • Save lukecampbell/eaffdd631eb4b8018e03458586f31c83 to your computer and use it in GitHub Desktop.
Save lukecampbell/eaffdd631eb4b8018e03458586f31c83 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
'''
split-certs.py
Splits certificates
'''
from __future__ import print_function
from argparse import ArgumentParser
import os
def main():
'''
Splits PEM encoded certificates
'''
parser = ArgumentParser(description=main.__doc__)
parser.add_argument('-i', '--input', default='-', help='File to read from, defaults to stdin')
parser.add_argument('output', default='.', help='Output directory to write certificates to')
args = parser.parse_args()
if args.input == '-':
file_content = sys.stdin.read()
else:
with open(args.input, 'r') as f:
file_content = f.read()
certs = []
buf = []
for line in file_content.split('\n'):
if line == '-----BEGIN CERTIFICATE-----':
buf = [line]
elif line == '-----END CERTIFICATE-----':
buf.append(line)
buf.append('')
certs.append('\n'.join(buf))
buf = []
else:
buf.append(line)
for i, cert in enumerate(certs):
path = os.path.join(args.output, '{}.crt'.format(str(i)))
with open(path, 'w') as f:
f.write(cert)
return 0
if __name__ == '__main__':
import sys
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment