主 题:50 行 Python 实现 SSL 证书过期监控,支持 Bark / Telegram 推送
发 布 者:opt7952
标签分类: Dev
时 间:2026-09-27 07:52:25
内容预览:手里域名和站点多了之后,SSL 证书过期是最容易被忽略的故障点。分享一个只用 Python 标准库实现的证书过期检查脚本:不依赖任何第三方包,直连 443 端口读取证书有效期,剩余天数不足阈值就推送告警,配合 cron 每天跑一次即可。原理用 ssl + socket 直连目标域名的 443 端口,完成 TLS 握手后读取对端证书的 notAfter 字段,换算成剩余天数,小于设定的阈值就触发推送。代码import sslimport socketimport datetimeimport jsonimport urllib.requestimport urllib.parseDOMAINS = ["example.com", "blog.example.com"]WARN_DAYS = 14def cert_expire_days(host, port=443): ctx = ssl.create_default_context() with socket.create_connection((host, port), timeout=10) as sock: with ctx.wrap_socket(sock, server_hostname=host) as ssock: cert = ssock.getpeercert() expire = datetime.datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z") return (expire - datetime.datetime.utcnow()).daysdef bark_push(key, title, body): url = "https://api.day.app/{}/{}
直达链接: https://www.nodeseek.com/post-950894-1
发 布 者:opt7952
标签分类: Dev
时 间:2026-09-27 07:52:25
内容预览:手里域名和站点多了之后,SSL 证书过期是最容易被忽略的故障点。分享一个只用 Python 标准库实现的证书过期检查脚本:不依赖任何第三方包,直连 443 端口读取证书有效期,剩余天数不足阈值就推送告警,配合 cron 每天跑一次即可。原理用 ssl + socket 直连目标域名的 443 端口,完成 TLS 握手后读取对端证书的 notAfter 字段,换算成剩余天数,小于设定的阈值就触发推送。代码import sslimport socketimport datetimeimport jsonimport urllib.requestimport urllib.parseDOMAINS = ["example.com", "blog.example.com"]WARN_DAYS = 14def cert_expire_days(host, port=443): ctx = ssl.create_default_context() with socket.create_connection((host, port), timeout=10) as sock: with ctx.wrap_socket(sock, server_hostname=host) as ssock: cert = ssock.getpeercert() expire = datetime.datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z") return (expire - datetime.datetime.utcnow()).daysdef bark_push(key, title, body): url = "https://api.day.app/{}/{}
直达链接: https://www.nodeseek.com/post-950894-1