linux中ssl证书到期提醒函数封装的核心是用openssl获取并解析证书有效期,通过date计算剩余天数,返回纯数字便于判断,再封装提醒逻辑实现生产可用性。

在 Linux 中,函数封装检测 SSL 证书到期提醒,核心是把“连接域名 → 提取证书 → 解析有效期 → 判断剩余天数 → 触发提醒”这一连串操作,抽象成可复用、可配置、易调用的 shell 函数。不追求大而全,重在清晰、稳定、能嵌入 cron 或脚本流程。
关键思路:用 openssl s_client 获取证书,用 openssl x509 -dates 解析时间,用 date -d 和 awk 算差值,最后按阈值决定是否记录或告警。
封装一个基础检测函数(纯 shell)
# 检测单个域名 SSL 证书剩余天数,返回整数(正数为剩余天数,负数为已过期,-1 为获取失败)
ssl_remaining_days() {
local domain="${1:-}"
local port="${2:-443}"
if [[ -z "$domain" ]]; then
echo -1
return
fi
# 获取证书的 notAfter 时间(如:notAfter=Dec 15 12:34:56 2026 GMT)
local not_after
not_after=$(echo | openssl s_client -connect "$domain:$port" -servername "$domain" 2>/dev/null | \
openssl x509 -noout -enddate 2>/dev/null | \
awk -F'= ' '{print $2}')
if [[ -z "$not_after" ]]; then
echo -1
return
fi
# 转换为秒级时间戳(支持常见 OpenSSL 输出格式)
local end_ts
end_ts=$(date -d "$not_after" +%s 2>/dev/null)
local now_ts=$(date +%s)
if [[ -z "$end_ts" || "$end_ts" == "invalid" ]]; then
echo -1
return
fi
local diff_sec=$((end_ts - now_ts))
echo $((diff_sec / 86400))
}
✅ 特点:无外部依赖(仅需
openssl和date),返回纯数字,方便后续逻辑判断。
Zynq Linux Hardware Debug下载Zynq‑7000 / Zynq UltraScale+ 硬件调试技能。适用于 Xilinx Zynq(Cortex‑A9/A53 + FPGA)Linux 环境,调试 I2C、I2S、UART、GPIO 等外设。包括设备树配置、内核驱动、用户空间调试工具、交叉编译和常见问题排查,支持 PetaLinux 开发。
封装一个带提醒逻辑的函数
# 检查并按阈值输出提醒(例如:剩余 ≤7 天时打印警告)
ssl_check_and_alert() {
local domain="$1"
local warn_days="${2:-7}"
local remaining
remaining=$(ssl_remaining_days "$domain")
case $remaining in
-1)
echo "[WARN] 无法获取 $domain 证书信息(连接失败/非 HTTPS/超时)"
;;
[0-9]*)
if [[ $remaining -le $warn_days && $remaining -ge 0 ]]; then
echo "[ALERT] $domain 证书将在 $remaining 天后过期!"
elif [[ $remaining -lt 0 ]]; then
echo "[ALERT] $domain 证书已过期 $(( -remaining )) 天!"
else
echo "[OK] $domain 证书剩余 $remaining 天"
fi
;;
*)
echo "[ERROR] ssl_remaining_days 返回异常值:$remaining"
;;
esac
}
✅ 特点:职责分离,复用上层函数;输出带状态标记,适配日志或通知链路。
实际使用示例(可直接粘贴运行)
# 测试单个域名
ssl_check_and_alert "www.google.com" 7
# 批量检查(配合 domains.txt)
while IFS= read -r d; do
[[ -z "$d" || "$d" =~ ^[[:space:]]*# ]] && continue
ssl_check_and_alert "$d" 10
done <p><code>domains.txt</code> 内容示例:</p><pre class="brush:php;toolbar:false;"># 生产站点
api.example.com
admin.example.com
shop.example.com进阶建议(按需添加)
-
加超时控制:用
timeout 5s包裹openssl s_client,防卡死 -
支持自定义端口:函数第二参数传
:8443,内部解析domain和port -
返回结构化数据:改用
printf "%s\t%d\n" "$domain" "$remaining"便于awk后处理 -
集成通知:在
[ALERT]分支里调用curl推送企业微信/钉钉,或mailx发邮件
不需要写类、不依赖 Python,一个函数搞定核心检测,再套一层逻辑就具备生产可用性。











