48 lines
1.4 KiB
Bash
Executable File
48 lines
1.4 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
|
|
# 用法:
|
|
# TLS_DOMAIN=api.example.com TLS_CERT_PORT=443 ./scripts/ops/check_cert_expiry.sh
|
|
|
|
TLS_DOMAIN="${TLS_DOMAIN:-api.example.com}"
|
|
TLS_CERT_PORT="${TLS_CERT_PORT:-443}"
|
|
TLS_MIN_DAYS="${TLS_MIN_DAYS:-15}"
|
|
OPS_ALERT_WEBHOOK="${OPS_ALERT_WEBHOOK:-}"
|
|
ALERT_TITLE="${ALERT_TITLE:-[wx_service] HTTPS 证书即将过期}"
|
|
|
|
send_alert() {
|
|
local message="$1"
|
|
if [[ -z "${OPS_ALERT_WEBHOOK}" ]]; then
|
|
echo "ALERT: ${message}" >&2
|
|
return
|
|
fi
|
|
|
|
curl -fsS -X POST "${OPS_ALERT_WEBHOOK}" \
|
|
-H "Content-Type: application/json" \
|
|
-d "{\"title\":\"${ALERT_TITLE}\",\"message\":\"${message}\"}" >/dev/null || true
|
|
}
|
|
|
|
if ! command -v openssl >/dev/null 2>&1; then
|
|
echo "openssl is required" >&2
|
|
exit 1
|
|
fi
|
|
|
|
expiry_line="$(echo | openssl s_client -servername "${TLS_DOMAIN}" -connect "${TLS_DOMAIN}:${TLS_CERT_PORT}" 2>/dev/null | openssl x509 -noout -enddate || true)"
|
|
if [[ -z "${expiry_line}" ]]; then
|
|
send_alert "无法获取 ${TLS_DOMAIN}:${TLS_CERT_PORT} 的证书过期时间。"
|
|
exit 1
|
|
fi
|
|
|
|
expiry_raw="${expiry_line#notAfter=}"
|
|
expiry_epoch="$(date -d "${expiry_raw}" +%s)"
|
|
now_epoch="$(date +%s)"
|
|
remaining_days="$(( (expiry_epoch - now_epoch) / 86400 ))"
|
|
|
|
if (( remaining_days <= TLS_MIN_DAYS )); then
|
|
send_alert "${TLS_DOMAIN} 证书将在 ${remaining_days} 天后过期,请尽快续期。"
|
|
exit 1
|
|
fi
|
|
|
|
echo "certificate valid: ${remaining_days} days remaining"
|
|
|