检测SSL证书过期时间
以下是shell检测ssl证书过期时间脚本:
#!/bin/bash
# 检查 domain.list 文件是否存在if [ ! -f "domain.list" ]; then echo "domain.list 文件不存在,请检查。" exit 1fi
# 遍历 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.listgaojinbo.comwww.jiangongdata.comEOF
优化说明:
- 异常处理:使用
openssl s_client
命令来获取证书信息,若无法获取证书信息(如连接超时、域名无效),会输出相应的错误信息到控制台和日志文件。 - 准确提取日期:使用
openssl x509 -noout -dates
命令提取证书的开始日期和过期日期,避免使用curl
可能出现的不准确问题。 - 代码可读性:使用
while
循环替代for
循环,结合IFS= read -r
读取文件内容,避免因域名包含空格等特殊字符而出现问题。
使用方法:
- 将上述脚本保存为一个文件,例如
check_cert.sh
。 - 添加执行权限:
chmod +x check_cert.sh
- 运行脚本:
./check_cert.sh
正在检查域名: gaojinbo.comgaojinbo.com开始日期: Feb 28 23:43:21 2025 GMT过期日期: May 29 23:43:20 2025 GMT正在检查域名: www.jiangongdata.comwww.jiangongdata.com开始日期: Jan 2 00:00:00 2025 GMT过期日期: Jan 2 23:59:59 2026 GMT
运行脚本后,会在 certs.log
文件中记录每个域名的证书开始日期和过期日期,若获取证书信息失败,也会记录相应的错误信息。