python监控网站证书有效期

import OpenSSL
import ssl
from datetime import datetime

'''
获取网站https证书有效期
'''

def main(domain):
    try:
        hostname = domain
        port = 443
        conn = ssl.create_connection((hostname, port))
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        sock = context.wrap_socket(conn, server_hostname=hostname)
        cert = ssl.DER_cert_to_PEM_cert(sock.getpeercert(True))
        x509 = OpenSSL.crypto.load_certificate(
            OpenSSL.crypto.FILETYPE_PEM, cert)
        start_date = str(x509.get_notBefore(), encoding='utf-8')
        expire_date = str(x509.get_notAfter(), encoding='utf-8')
        # time 字符串转时间数组
        start_date = datetime.strptime(start_date, "%Y%m%d%H%M%SZ")
        # datetime 字符串转时间数组
        expire_date = datetime.strptime(expire_date, "%Y%m%d%H%M%SZ")
        # 剩余天数
        remain_days = (expire_date-datetime.now()).days
        print('{} ssl start_date,expire_date,remain_days is {},{},{}'.format(
            domain, start_date, expire_date, remain_days))
        return start_date, expire_date, remain_days
    except Exception as e:
        print('{} {}'.format(e.__traceback__.tb_lineno, e))
        return datetime.now(), datetime.now(), -999999999

if __name__ == "__main__":
    remain_days = main('www.guojingyi.cn')
    print(remain_days)

标签: python

评论已关闭