检测ssl证书到期时间告警脚本

0,安装python3及依赖。

yum install python3-pip
pip3 install -U pip
pip3 install requests
pip3 install python-dateutil

1,脚本内容

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import ssl, socket
import requests
from dateutil import parser
import pytz
import datetime
import telegram

expire_domain_list = []
day_list = []
# 告警函数,填写你小飞机bot的token和指定组id
def telegram_alarm(message):
    bot = telegram.Bot(token='1645507005:AAFSOD8kx_-SylYr3SDFHdiiCosMmdEPVQA')
    bot.send_message(chat_id=-52222222222, text=message)

def parse(time_str):
    """
    Parse time format.
    :param time_str: <str> time string
    :return: <datetime.date> date
    """
    # 使用split()函数将字符串转化为列表,并分解出年月日
    time_list = time_str.split("-")
    year = time_list[0]
    month = time_list[1]
    day = time_list[2]
    # 将日期转换为datetime.date格式并返回
    return datetime.date(int(year), int(month), int(day))

def get_my_domain(mydomain):
    try:
        c = ssl.create_default_context()
        s = c.wrap_socket(socket.socket(), server_hostname=mydomain)
        s.connect((mydomain, 443))
        my_cert = s.getpeercert()
        get_my_cert_dated(mydomain, my_cert)
    except ssl.CertificateError and socket.gaierror as e:
        pass


def get_my_cert_dated(domain, certs):
    cert_end_time = parser.parse(certs['notAfter']).astimezone(pytz.utc)
    aaa = str(cert_end_time).split()[0]
    f = datetime.datetime.now()
    s = datetime.datetime.strftime(f, "%Y-%m-%d")
    global Days
    Days = (parse(aaa)-parse(s)).days
    print(domain,Days)
    # 告警阈值,证书小于10天就触发告警
    if Days < 10:
        expire_domain_list.append(domain)
        day_list.append(Days)

# 域名存放文件,/python/domain.list。把需要监控的域名写进文件里,如: baidu.com|x5.qq.com
def read_domain_files():
    with open('/python/domain.list', 'r', encoding="utf-8") as file:
        for domain in file:
            try:
                get_my_domain(domain.strip())
            except:
                pass

if __name__ == "__main__":
    read_domain_files()

format_info = ''
for i in expire_domain_list[:10]:
    format_info = format_info + i + '\n'

if len(expire_domain_list) < 10 and len(expire_domain_list) > 0:
    telegram_alarm(message='即将过期的api域名有(小于{}天): {}'.format(min(day_list), format_info))

elif len(expire_domain_list) > 10:
    telegram_alarm(message='即将过期的api域名有(小于{}天): {}'.format(min(day_list), format_info))
    telegram_alarm(message='默认只显示10条, 剩余{}个要过期域名存放在"/tmp/expire_api.log"文件里.'.format(len(expire_domain_list[10:])))
    expire_api_file=open('/tmp/expire_api.log', 'w')
    for i in expire_domain_list[10:]:
        expire_api_file.write(i+'\n')

2,使用方法

python3 脚本名称.py

Snipaste_2021-04-01_15-32-34.png