一起学习网 一起学习网


定时监控域名证书是否过期

运维 SSL证书监控,证书过期提醒,Python脚本,企业微信Webhook,crontab定时任务 06-07

1. Python 监控脚本

保存为:

check_ssl_expire.py

内容如下:

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

import ssl
import socket
import datetime
import requests
# 企业微信申请通知地址
WEBHOOK_URL = ""
# 监控域名数组
DOMAINS = [
    "www.baidu.com"
]

# 提前几天通知
ALERT_DAYS = 3

TIMEOUT = 10


def get_ssl_expire_date(domain, port=443):
    context = ssl.create_default_context()

    with socket.create_connection((domain, port), timeout=TIMEOUT) as sock:
        with context.wrap_socket(sock, server_hostname=domain) as ssock:
            cert = ssock.getpeercert()

    not_after = cert.get("notAfter")
    expire_date = datetime.datetime.strptime(
        not_after,
        "%b %d %H:%M:%S %Y %Z"
    )

    return expire_date


def send_wecom_message(content):
    payload = {
        "msgtype": "text",
        "text": {
            "content": content
        }
    }

    try:
        response = requests.post(WEBHOOK_URL, json=payload, timeout=10)
        print(response.text)
    except Exception as e:
        print(f"发送企业微信通知失败: {e}")


def main():
    now = datetime.datetime.utcnow()
    alerts = []

    for domain in sorted(set(DOMAINS)):
        try:
            expire_date = get_ssl_expire_date(domain)
            remaining = expire_date - now
            remaining_days = remaining.days

            print(f"{domain} 证书过期时间: {expire_date} UTC,剩余 {remaining_days} 天")

            if remaining_days < 0:
                alerts.append(
                    f"❌ {domain}\n"
                    f"证书已过期\n"
                    f"过期时间:{expire_date} UTC"
                )
            elif remaining_days <= ALERT_DAYS:
                alerts.append(
                    f"⚠️ {domain}\n"
                    f"证书即将过期\n"
                    f"过期时间:{expire_date} UTC\n"
                    f"剩余天数:{remaining_days} 天"
                )

        except Exception as e:
            alerts.append(
                f"❌ {domain}\n"
                f"证书检查失败:{e}"
            )

    if alerts:
        content = "SSL 证书过期提醒\n\n" + "\n\n".join(alerts)
        send_wecom_message(content)
    else:
        print("所有证书均未达到告警阈值,无需通知。")


if __name__ == "__main__":
    main()

2. 安装依赖

pip3 install requests

3. 手动测试

python3 check_ssl_expire.py

如果有证书将在 3 天内过期,企业微信机器人会收到通知。


4. 设置每天自动检查

执行:

crontab -e

添加一行,例如每天上午 9 点检查:

0 9 * * * /usr/bin/python3 /path/to/check_ssl_expire.py >> /var/log/check_ssl_expire.log 2>&1

请把 /path/to/check_ssl_expire.py 改成你的真实脚本路径。



编辑:一起学习网