Get the SSL certificate expiration period using timedelta
$ ./cert_expires.py example.com google.com example.com: 1093 days google.com: 76 days
#!/usr/bin/env python # thanks: http://qiita.com/uemura/items/a3a0937f77494e62213c import sys import re import subprocess import datetime def parse_result_date_string(date_string): """ convert date string to datetime >>> date_string = "Feb 2 05:47:50 2015 GMT" >>> d = parse_result_date_string(date_string) >>> d datetime.datetime(2015, 2, 2, 5, 47, 50) """ d = datetime.datetime.strptime(date_string, '%b %d %H:%M:%S %Y %Z') return d re_start = re.compile(r'Not Before: (.+)') re_end = re.compile(r'Not After : (.+)') def get_date_strings_from_result(result): """ :return: cert start date, cert expire date >>> text = "Not Before: Feb 2 05:47:47 2015 GMT\\n" \\ ... "Not After : Feb 4 16:03:29 2016 GMT" >>> get_date_strings_from_result(text) ('Feb 2 05:47:47 2015 GMT', 'Feb 4 16:03:29 2016 GMT') """ rr_start = re_start.search(result) rr_end = re_end.search(result) return rr_start.group(1) if rr_start else None, \ rr_end.group(1) if rr_end else None def get_cert_start_expire_date(domain): """ :return: cert start date, cert expire date """ command = "openssl s_client -connect {}:443 < /dev/null " \ "2> /dev/null | openssl x509 -text | grep Not" command = command.format(domain) out = subprocess.check_output(command, shell=True) ss, es = get_date_strings_from_result(out) return parse_result_date_string(ss), parse_result_date_string(es) def get_cert_expire_delta(domain): """ time delta cert expire date and now """ start_date, expire_date = get_cert_start_expire_date(domain) return expire_date - datetime.datetime.now() def main(): for domain in sys.argv[1:]: delta = get_cert_expire_delta(domain) print('{}: {} days'.format(domain, delta.days)) if __name__ == '__main__': main()
Reference: http://qiita.com/uemura/items/a3a0937f77494e62213c
Comments