如果我在Mac或Linux中有实际文件和Bash Shell,我如何查询cert文件何时到期?假设我有csr,key,pem和chain文件,这不是一个网站,而是实际上是证书文件本身。
使用openssl
:
openssl x509 -enddate -noout -in file.pem
输出在表单上:
notAfter=Nov 3 22:23:50 2014 GMT
另请参阅 MikeW的答案 如何轻松检查证书是否已过期,或者是否在一定时间内,无需解析上述日期。
如果您只想知道证书是否已过期(或将在接下来的N秒内完成),-checkend <seconds>
的openssl x509
选项将告诉您:
if openssl x509 -checkend 86400 -noout -in file.pem
then
echo "Certificate is good for another day!"
else
echo "Certificate has expired or will do so within 24 hours!"
echo "(or is invalid/not found)"
fi
这节省了必须自己进行日期/时间比较。
如果证书尚未过期,则openssl
将返回0
(零)的退出代码,并且在上面的示例中将不会在接下来的86400秒内返回。如果证书已过期或已经过期 - 或者其他错误,如无效/不存在的文件 - 返回码为1
。
(当然,它假定时间/日期设置正确)
这是我的bash命令行,按顺序列出多个证书,最近一次到期。
for pem in /etc/ssl/certs/*.pem; do
printf '%s: %s\n' \
"$(date --date="$(openssl x509 -enddate -noout -in "$pem"|cut -d= -f 2)" --iso-8601)" \
"$pem"
done | sort
样本输出:
2015-12-16: /etc/ssl/certs/Staat_der_Nederlanden_Root_CA.pem
2016-03-22: /etc/ssl/certs/CA_Disig.pem
2016-08-14: /etc/ssl/certs/EBG_Elektronik_Sertifika_Hizmet_S.pem
这是一个bash函数,它会检查您的所有服务器,假设您使用的是DNS循环法。请注意,这需要GNU date,并且不适用于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
对于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
标志。
如果证书在一段时间后过期(例如15天),则一行检查true/false:
if openssl x509 -checkend $(( 24*3600*15 )) -noout -in <(openssl s_client -showcerts -connect may.domain.com:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
then
echo 'good'
else
echo 'bad'
fi
如果(出于某种原因)你想在Linux中使用GUI应用程序,请使用gcr-viewer
(在大多数发行版中,它由包gcr
安装(否则在包gcr-viewer
中))
gcr-viewer file.pem
# or
gcr-viewer file.crt