Linux 系统使用命令行工具查看 TLS/SSL 效期时间


目录
  • 1] 通弄服务器地址和域名查看证书有效期
    • 通过openssl命令行查看域名有效期
    • 通过curl命令行获取 证书有效期信息
  • 2] 通过查看证书文件获取证书有效期信息

1] 通弄服务器地址和域名查看证书有效期

通过openssl命令行查看域名有效期

例如我们想查看”www.cnblogs.com”的域名证书剩余有效期,则可以使用如下命令:

cat << "EOF" > ./check_expire.sh
domain="www.cnblogs.com"
PORT="443"
time_formatted=$(openssl s_client -servername $domain -connect $domain:$PORT 2>/dev/null | openssl x509 -noout -dates 2>/dev/null |grep notAfter|cut -d '=' -f2)
time_string=$(date -d "$time_formatted" +%s)
time_current=$(date +%s)
day_left=$(echo "($time_string - $time_current)/( 3600 * 24)"|bc)
echo $day_left
EOF
sh ./check_expire.sh
rm -f ./check_expire.sh

OpenSSL 客户端的各参数意义如下:

  • s_client:指示 OpenSSL 工具实现一个 SSL/TLS 客户端,通过 SSL/TLS 连接到远程主机
  • -servername:设置 TLS SNI(Server Name Indication),用于设置连接的远程主机
  • -connect:设置连接的主机及端口
  • x509:运行显示证书和签名实用工具
  • -noou:不输出证书的编码版本
  • -dates:显示证书的效期时间信息
    输出结果信息中的”notBefore”和”notAfter”则为证书效期的起止时间。

通过curl命令行获取 证书有效期信息

例如

cat << "EOF" > ./check_expire.sh
domain="www.cnblogs.com"
time_raw=$(curl -vIs https://$domain 2>&1 |grep "expire date"|awk -F 'expire date:' '{print $2}')
time_string=$(date -d "$time_raw" +%s)
time_current=$(date +%s)
day_left=$(echo "($time_string - $time_current)/(3600*24)"|bc)
echo $day_left
EOF
sh ./check_expire.sh
rm -f ./check_expire.sh

2] 通过查看证书文件获取证书有效期信息

cert_path="/path/to/domain.crt"
time_raw=$(openssl x509 -enddate  -noout -in $cert_path|awk -F "notAfter=" '{print $2}')
time_string=$(date -d "$time_raw" +%s)
time_current=$(date +%s)
day_left=$(echo "($time_string - $time_current)/(3600*24)"|bc)
echo $day_left