如果我在Mac或Linux中有实际的文件和Bash shell,我如何查询证书文件何时到期?不是网站,实际上是证书文件本身,假设我有csr、key、pem和chain文件。


当前回答

与接受的答案相同,但请注意,它甚至适用于。crt文件,而不仅仅是。pem文件,以防万一,如果你无法找到。pem文件的位置。

openssl x509 -enddate -noout -in e71c8ea7fa97ad6c.crt

结果:

notAfter=Mar 29 06:15:00 2020 GMT

其他回答

与接受的答案相同,但请注意,它甚至适用于。crt文件,而不仅仅是。pem文件,以防万一,如果你无法找到。pem文件的位置。

openssl x509 -enddate -noout -in e71c8ea7fa97ad6c.crt

结果:

notAfter=Mar 29 06:15:00 2020 GMT

对于MAC OSX (El Capitan),我对Nicholas的例子进行了修改。

for pem in /path/to/certs/*.pem; do
    printf '%s: %s\n' \
        "$(date -jf "%b %e %H:%M:%S %Y %Z" "$(openssl x509 -enddate -noout -in "$pem"|cut -d= -f 2)" +"%Y-%m-%d")" \
    "$pem";
done | sort

样例输出:

2014-12-19: /path/to/certs/MDM_Certificate.pem
2015-11-13: /path/to/certs/MDM_AirWatch_Certificate.pem

macOS不喜欢我系统上的——date=或——iso-8601标志。

如果(出于某种原因)您想在Linux中使用GUI应用程序,请使用gcr-viewer(在大多数发行版中,它是由包gcr安装的(否则在包gcr-viewer中))

gcr-viewer file.pem
# or
gcr-viewer file.crt

这里有一个bash函数,它检查所有服务器,假设您使用的是DNS循环。注意,这需要GNU日期,不能在Mac OS上工作

function check_certs () {
  if [ -z "$1" ]
  then
    echo "domain name missing"
    exit 1
  fi
  name="$1"
  shift

  now_epoch=$( date +%s )

  dig +noall +answer $name | while read _ _ _ _ ip;
  do
    echo -n "$ip:"
    expiry_date=$( echo | openssl s_client -showcerts -servername $name -connect $ip:443 2>/dev/null | openssl x509 -inform pem -noout -enddate | cut -d "=" -f 2 )
    echo -n " $expiry_date";
    expiry_epoch=$( date -d "$expiry_date" +%s )
    expiry_days="$(( ($expiry_epoch - $now_epoch) / (3600 * 24) ))"
    echo "    $expiry_days days"
  done
}

输出的例子:

$ check_certs stackoverflow.com
151.101.1.69: Aug 14 12:00:00 2019 GMT    603 days
151.101.65.69: Aug 14 12:00:00 2019 GMT    603 days
151.101.129.69: Aug 14 12:00:00 2019 GMT    603 days
151.101.193.69: Aug 14 12:00:00 2019 GMT    603 days

一行检查true/false,如果域名证书将在一段时间后过期(例如。15天):

openssl x509 -checkend $(( 24*3600*15 )) -noout -in <(openssl s_client -showcerts -connect my.domain.com:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
if [ $? -eq 0 ]; then
  echo 'good'
else
  echo 'bad'
fi