场景
下面这个脚本,放到定时任务里跑,可以检查https证书过期时间,并告警
关键词:
- SSL证书过期
- HTTPS证书过期
- 证书过期检查
- 证书检查脚本
- https expire check
- ssl check
- cert check
由于date命令兼容问题,该脚本不支持MacOS,在CentOS环境下测试有效
脚本全文
#!/usr/bin/env bash
#filename: https-cert-expire-check.sh
# this script is used to check the domain expired and alert
# 直接传入参数 print 可以打印域名,即过期时间
EXPIRE_ALERT_DAY=30 #if domain https cert expire day less than this, then alert to sae team
TMP_PATH=/tmp/https_expire.txt
DEPLOY_IP=192.168.1.10 #这里是告警用的,可以替换成实际的内网IP
SAE_HTTPS_DOMAINS=(
https://www.baidu.com
https://www.jd.com
)
if [ "$1" = "print" ]; then
echo "Domain Expire"
for domain in ${SAE_HTTPS_DOMAINS[*]}; do
curl -v "${domain}" &> ${TMP_PATH}
EXPIRE_TIME_GMT=$(grep 'expire date' ${TMP_PATH} | awk -F ': ' '{print $2}')
#change gmt time to beijing time
EXPIRE_TIME_CST=$(date -d "${EXPIRE_TIME_GMT}" +%F)
echo "${domain} ${EXPIRE_TIME_CST}"
done
exit
fi
#change day to seconds
EXPIRE_ALERT_SECONDS=$(( EXPIRE_ALERT_DAY * 24 * 60 * 60 ))
for domain in ${SAE_HTTPS_DOMAINS[*]}; do
curl -v "${domain}" &> ${TMP_PATH}
EXPIRE_TIME_GMT=$(grep 'expire date' ${TMP_PATH} | awk -F ': ' '{print $2}')
EXPIRE_TIME_CST_SECONDS=$(date -d "${EXPIRE_TIME_GMT}" +%s)
CURRENT_TIME_CST_SECONDS=$(date +%s)
EXPIRE_SECONDS=$(( EXPIRE_TIME_CST_SECONDS - CURRENT_TIME_CST_SECONDS ))
# after EXPIRE_SECONDS the domain https expired, if
# this seconds less than EXPIRE_ALERT_SECONDS, alert
if [ $EXPIRE_SECONDS -lt $EXPIRE_ALERT_SECONDS ]; then
# echo "$domain EXPIRE_SECONDS:$EXPIRE_SECONDS EXPIRE_ALERT_SECONDS:$EXPIRE_ALERT_SECONDS"
/etc/send_alert.py -s https-cert-expire-check -c "$DEPLOY_IP" -l error -S "$DEPLOY_IP" "${domain} https almost expired you should check"
fi
done
# test manually you can do like this
# curl -v https://www.jd.com &> /tmp/tmp.txt && egrep 'expire date' /tmp/tmp.txt