证书过期会导致服务不可用,提前监控证书有效期是运维的基本功。OpenSSL 提供了多种检查证书有效期的方法。

检查远程服务器证书

查看有效期

1
echo | openssl s_client -connect www.baidu.com:443 -servername www.baidu.com 2>/dev/null | openssl x509 -noout -dates

输出:

1
2
notBefore=Jul  9 07:01:02 2025 GMT
notAfter=Aug 10 07:01:01 2026 GMT
  • notBefore:证书生效日期
  • notAfter:证书过期日期

检查本地证书文件

1
openssl x509 -in certificate.crt -noout -dates

查看剩余天数

1
openssl x509 -in certificate.crt -noout -checkend 0

输出:

  • Certificate will not expire:证书未过期
  • Certificate will expire:证书已过期

检查是否在 30 天内过期(2592000 秒):

1
openssl x509 -in certificate.crt -noout -checkend 2592000

返回码:

  • 0:证书在指定时间内不会过期
  • 1:证书已过期或将在指定时间内过期

批量检查脚本

检查多个域名

1
2
3
4
5
6
7
8
#!/bin/bash
domains=("www.baidu.com" "www.google.com" "github.com")

for domain in "${domains[@]}"; do
    echo "=== $domain ==="
    echo | openssl s_client -connect "$domain:443" -servername "$domain" 2>/dev/null | \
        openssl x509 -noout -dates 2>/dev/null
done

计算剩余天数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#!/bin/bash
domain="www.baidu.com"

expiry=$(echo | openssl s_client -connect "$domain:443" -servername "$domain" 2>/dev/null | \
    openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2)

expiry_epoch=$(date -d "$expiry" +%s)
now_epoch=$(date +%s)
days=$(( (expiry_epoch - now_epoch) / 86400 ))

echo "证书将在 $days 天后过期"

常用参数说明

参数 说明
-dates 显示生效和过期日期
-startdate 只显示生效日期
-enddate 只显示过期日期
-checkend N 检查是否在 N 秒内过期

实际示例

检查百度证书有效期:

1
echo | openssl s_client -connect www.baidu.com:443 -servername www.baidu.com 2>/dev/null | openssl x509 -noout -dates

输出:

1
2
notBefore=Jul  9 07:01:02 2025 GMT
notAfter=Aug 10 07:01:01 2026 GMT

监控建议

  1. 设置告警阈值:提前 30 天告警
  2. 自动化检查:配合 cron 定时执行
  3. 多域名监控:批量检查所有业务域名
  4. 记录日志:保存检查结果便于追溯

总结

使用 openssl s_client 配合 openssl x509 可以快速检查远程或本地证书的有效期,适合集成到监控脚本中实现自动化告警。