且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:获取ssl证书信息和到期时间

更新时间:2022-05-15 01:22:55

1、通过证书获取

openssl x509 -in <cert>.pem -noout -dates

2、通过域名获取

echo | openssl s_client -servername <doman> -connect <doman>:443 2>/dev/null | openssl x509 -noout -dates

3、通过脚本获取

# coding: utf-8 
# 查询域名证书到期情况

import re
import subprocess
from datetime import datetime


def get_re_match_result(pattern, string):
    match = re.search(pattern, string)
    return match.group(1)


def parse_time(date_str):
    return datetime.strptime(date_str, "%b %d %H:%M:%S %Y GMT")


def format_time(date_time):
    return datetime.strftime(date_time, "%Y-%m-%d %H:%M:%S")


def get_cert_info(domain):
    """获取证书信息"""
    cmd = f"curl -Ivs https://{domain} --connect-timeout 10"

    exitcode, output = subprocess.getstatusoutput(cmd)

    # 正则匹配
    start_date = get_re_match_result('start date: (.*)', output)
    expire_date = get_re_match_result('expire date: (.*)', output)

    # 解析匹配结果
    start_date = parse_time(start_date)
    expire_date = parse_time(expire_date)

    return {
        'start_date': start_date,
        'expire_date': expire_date
    }


def get_cert_expire_date(domain):
    """获取证书剩余时间"""
    info = get_cert_info(domain)
    print(info)

    expire_date = info['expire_date']

    # 剩余天数
    return (expire_date - datetime.now()).days


if __name__ == "__main__":
    domain = 'www.baidu.com'
    expire_date = get_cert_expire_date(domain)
    print(expire_date)

参考

查看域名https证书到期时间

基于python检查SSL证书到期情况代码实例