Ubuntu上监控Nginx SSL的实用方案
一 监控目标与总体思路
二 命令行快速核查
openssl x509 -in /path/to/cert.pem -noout -datesopenssl x509 -noout -modulus -in /path/to/cert.pem | openssl md5 与 openssl rsa -noout -modulus -in /path/to/key.pem | openssl md5,两者哈希应一致。echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -datesopenssl s_client -connect example.com:443 -servername example.comsystemctl is-active nginx && ss -lntp | grep ':443\|:80'curl -s http://127.0.0.1/nginx_status三 脚本化巡检与阈值告警
bash check_ssl.sh /etc/nginx/ssl/site.crt https://example.com 30#!/usr/bin/env bash
set -Eeuo pipefail
CERT_FILE="$1"
URL="$2"
WARN_DAYS="${3:-30}"
now_ts=$(date +%s)
# 本地证书到期天数
if [[ -f "$CERT_FILE" ]]; then
exp_str=$(openssl x509 -in "$CERT_FILE" -noout -enddate | cut -d= -f2)
exp_ts=$(date -d "$exp_str" +%s)
days_left=$(( (exp_ts - now_ts) / 86400 ))
echo "local_cert_days_left=$days_left"
if (( days_left <= WARN_DAYS )); then
echo "CRITICAL: $CERT_FILE 剩余 $days_left 天"
exit 2
elif (( days_left <= WARN_DAYS * 2 )); then
echo "WARNING: $CERT_FILE 剩余 $days_left 天"
exit 1
else
echo "OK: $CERT_FILE 剩余 $days_left 天"
exit 0
fi
fi
# 远端证书到期天数(SNI)
domain=$(echo "$URL" | awk -F/ '{print $3}')
exp_str=$(echo | openssl s_client -connect "$domain:443" -servername "$domain" 2>/dev/null \
| openssl x509 -noout -enddate | cut -d= -f2)
exp_ts=$(date -d "$exp_str" +%s)
days_left=$(( (exp_ts - now_ts) / 86400 ))
echo "remote_cert_days_left=$days_left"
if (( days_left <= WARN_DAYS )); then
echo "CRITICAL: $URL 剩余 $days_left 天"
exit 2
elif (( days_left <= WARN_DAYS * 2 )); then
echo "WARNING: $URL 剩余 $days_left 天"
exit 1
else
echo "OK: $URL 剩余 $days_left 天"
exit 0
fi
0 2 * * * root /usr/local/bin/check_ssl.sh /etc/nginx/ssl/site.crt https://example.com 30 >> /var/log/ssl_check.log 2>&1sudo systemctl reload nginx 使新证书生效,无需重启服务。四 可视化监控与告警集成