Skip to content

检测SSL证书过期时间

以下是shell检测ssl证书过期时间脚本:

#!/bin/bash
# 检查 domain.list 文件是否存在
if [ ! -f "domain.list" ]; then
echo "domain.list 文件不存在,请检查。"
exit 1
fi
# 遍历 domain.list 中的每个域名
while IFS= read -r domain; do
echo "正在检查域名: $domain"
# 尝试获取证书信息
cert_info=$(echo | openssl s_client -servername "$domain" -connect "$domain:443" 2>/dev/null | openssl x509 -noout -dates 2>/dev/null)
if [ -z "$cert_info" ]; then
echo "无法获取 $domain 的证书信息,可能是连接超时或域名无效。" >> certs.log
echo "无法获取 $domain 的证书信息,可能是连接超时或域名无效。"
echo "" >> certs.log
continue
fi
# 提取开始日期和过期日期
start_date=$(echo "$cert_info" | grep "notBefore" | cut -d= -f2)
expire_date=$(echo "$cert_info" | grep "notAfter" | cut -d= -f2)
# 输出结果到控制台和日志文件
echo "$domain" | tee -a certs.log
echo "开始日期: $start_date" | tee -a certs.log
echo "过期日期: $expire_date" | tee -a certs.log
echo "" >> certs.log
done < domain.list
cat <<EOF > domain.list
gaojinbo.com
www.jiangongdata.com
EOF

优化说明:

  1. 异常处理:使用 openssl s_client 命令来获取证书信息,若无法获取证书信息(如连接超时、域名无效),会输出相应的错误信息到控制台和日志文件。
  2. 准确提取日期:使用 openssl x509 -noout -dates 命令提取证书的开始日期和过期日期,避免使用 curl 可能出现的不准确问题。
  3. 代码可读性:使用 while 循环替代 for 循环,结合 IFS= read -r 读取文件内容,避免因域名包含空格等特殊字符而出现问题。

使用方法:

  1. 将上述脚本保存为一个文件,例如 check_cert.sh
  2. 添加执行权限:
Terminal window
chmod +x check_cert.sh
  1. 运行脚本:
Terminal window
./check_cert.sh
正在检查域名: gaojinbo.com
gaojinbo.com
开始日期: Feb 28 23:43:21 2025 GMT
过期日期: May 29 23:43:20 2025 GMT
正在检查域名: www.jiangongdata.com
www.jiangongdata.com
开始日期: Jan 2 00:00:00 2025 GMT
过期日期: Jan 2 23:59:59 2026 GMT

运行脚本后,会在 certs.log 文件中记录每个域名的证书开始日期和过期日期,若获取证书信息失败,也会记录相应的错误信息。