7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SSL証明書の有効期限を取得するスクリプト

Posted at

こちらを参考にしました。
http://qiita.com/uemura/items/a3a0937f77494e62213c

import して使うことを想定

コマンドから使うと

$ ./cert_expires.py example.com google.com
example.com: 1093 days
google.com: 76 days
sert_expires.py
# !/usr/bin/env python


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()
7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?