目的是检查网站是否过期,过期前几天进行通知

import subprocess
from datetime import datetime, timedelta, timezone
import requests
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()

# 发送通知请求
def send_msg_to_gotify(title, msg):
    url = "http://152.136.153.72:8385/message"
    params = {"token": "AI.53prwavAZsoC"}
    current_time = datetime.now()
    # 表单数据
    data = {
        "title": title,
        "message": msg,
        "priority": "0"
    }
    try:
        response = requests.post(
            url,
            params=params,
            data=data
        )
        print("Response Body:", response.text)
    except requests.exceptions.RequestException as e:
        print("请求失败:", e)

def check_ssl_certificate_expiration(web_site, out_date):
    # 执行 openssl 命令获取证书信息
    try:
        result = subprocess.run(
            ["openssl", "x509", "-in", "fullchain.pem", "-noout", "-dates"],
            capture_output=True,
            text=True,
            check=True,
            cwd=f"C:\\Certbot\\live\\{web_site}"
        )
    except subprocess.CalledProcessError as e:
        print("执行 openssl 命令失败:", e)
        return

    # 解析输出,提取 notAfter 日期
    output = result.stdout
    not_after_str = None
    for line in output.splitlines():
        if line.startswith("notAfter="):
            not_after_str = line.split("=", 1)[1].strip()
            break

    if not not_after_str:
        print("未找到 notAfter 信息")
        return

    # 解析日期字符串为 datetime 对象(使用 GMT 时间)
    try:
        date_format = "%b %d %H:%M:%S %Y GMT"
        not_after_date = datetime.strptime(not_after_str, date_format).replace(tzinfo=timezone.utc)
    except ValueError as e:
        print("日期解析失败:", e)
        return

    # 获取当前 UTC 时间
    current_date = datetime.now(timezone.utc)

    # 计算时间差
    delta = not_after_date - current_date

    # 判断是否在 15 天内且未过期
    if 0 <= delta.days <= out_date:
        print(f"⚠️ SSL 证书({web_site})将在 {delta.days} 天后过期,请及时续期!")
        send_msg_to_gotify('SSL即将过期', f'SSL 证书({web_site})将在 {delta.days} 天后过期,请及时更新并重启nginx服务')
    elif delta.days < 0:
        print(f"❌ SSL 证书({web_site})已过期!")
        send_msg_to_gotify('SSL即将过期', f'SSL 证书({web_site})已过期,请及时更新并重启nginx服务')
    else:
        print(f"✅ SSL 证书({web_site})有效期超过 {out_date} 天,无需处理。")


# 执行检查
@scheduler.scheduled_job('cron', hour=8, minute=30, misfire_grace_time=3600)
def tick():
    check_ssl_certificate_expiration('cx.sdasinfo.org.cn', 15)

try:
    scheduler.start()
    print('定时任务成功执行')
except Exception as e:
    scheduler.shutdown()
    print('定时任务执行失败')
finally:
    exit()
最后修改:2025 年 07 月 26 日
如果觉得我的文章对你有用,请随意赞赏