很久没更新个人博客了,发个简单的Python脚本示意自己还在更新,哈哈
检查证书有效期,有效期15天以内,通过钉钉机器人提醒,钉钉提醒的python脚本可在官方查看
安装库:

pip3 install python-dateutil pyopenssl

python脚本:

# -*- coding: utf-8 -*-
import datetime
import OpenSSL
import configparser
from dateutil import parser
from common.dingding import Ding
from common.logger import logs

# 检查证书时间
def check_cert(paths):
    with open(paths, "rb") as fp:
        crt_data = fp.read()
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, crt_data)
    # 有效期从(2021-06-11 04:11:39.588770+00:00,用tzinfo=None去掉时区+00:00)
    datetime_before = parser.parse(cert.get_notBefore().decode("UTF-8")).replace(tzinfo=None)
    # 有效期到
    datetime_after = parser.parse(cert.get_notAfter().decode("UTF-8")).replace(tzinfo=None)
    return datetime_before, datetime_after

# 获取证书文件路径,并检查证书距今还有多少天,通过钉钉提醒
def main():
    # 读取配置文件
    dict_certs = certs()
    # print(dict_certs)
    # 检查证书
    for n in dict_certs.keys():
        before, after = check_cert(dict_certs[n])
        # print(f'{n} 有效期从:', before)
        # print(f'{n} 到:', after)
        now = datetime.datetime.now()
        # 检查证书还有多少天到期
        time_difference = (after - now).days
        if time_difference >= 0 and time_difference <= 15:
            log.logger.info(f'域名 - {n}:\n'
                            f'证书还有{time_difference}天到期\n'
                            f'证书到期时间:{after}')
            dd.dingding_request(f'域名 - {n}:\n'
                                f'证书还有{time_difference}天到期\n'
                                f'证书到期时间:{after}')
        elif time_difference < 0:
            log.logger.info(f'域名 - {n}:\n'
                            f'证书已经过期{-time_difference}天\n'
                            f'证书到期时间:{after}')
            dd.dingding_request(f'域名 - {n}:\n'
                                f'证书已经过期{-time_difference}天\n'
                                f'证书到期时间:{after}')

# 读取config.conf中的证书文件路径:baidu.com = ./certs/baidu/www.baidu.com.crt
def certs():
    config = configparser.ConfigParser()
    configfile = './conf/config.conf'
    config.read(configfile, encoding='utf-8')
    paths = [config['certs'][path] for path in config.options('certs')]
    path_options = config.options('certs')
    # 两个列表合成字典
    paths_dict = dict(zip(path_options, paths))
    # print(paths_dict)
    return paths_dict

if __name__ == '__main__':
    # 创建Ding类(钉钉)的对象dd
    dd = Ding()
    # 创建Logger类(日志)的对象log
    log = logs(f'./logs/certs_{datetime.datetime.now().strftime("%Y-%m-%d")}.log')
    main()