定时检测域名ssl证书是否过期

原理说明

使用openssl从域名证书中提取有效期,并对其处理

提取结束时间

注意:语句中$host,$port需替换为真实域名及端口

1
openssl s_client -servername $host -host $host -port $port -showcerts </dev/null 2>/dev/null | sed -n '/BEGIN CERTIFICATE/,/END CERT/p' | openssl x509 -text 2>/dev/null | sed -n 's/ *Not After : *//p'

这里以www.baidu.com为例
1
openssl s_client -servername www.baidu.com -host www.baidu.com -port 443 -showcerts </dev/null 2>/dev/null | sed -n '/BEGIN CERTIFICATE/,/END CERT/p' | openssl x509 -text 2>/dev/null | sed -n 's/ *Not After : *//p'

图片1

计算剩余时间(天)

1
2
3
4
5

end_date_seconds=`date '+%s' --date "May 26 05:31:02 2019 GMT"`
now_seconds=`date '+%s'`
echo "($end_date_seconds-$now_seconds)/24/3600" | bc

完整脚本check-cert-expire-host.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#!/bin/sh

host=$1
port=$2
end_date=`openssl s_client -servername $host -host $host -port $port -showcerts </dev/null 2>/dev/null | sed -n '/BEGIN CERTIFICATE/,/END CERT/p' | openssl x509 -text 2>/dev/null | sed -n 's/ *Not After : *//p'`

if [ -n "$end_date" ]
then
end_date_seconds=`date '+%s' --date "$end_date"`
now_seconds=`date '+%s'`
echo "($end_date_seconds-$now_seconds)/24/3600" | bc
fi

使用方式 ./check-cert-expire-host.sh www.baidu.com 443

使用域名列表及发送钉钉通知

脚本名check-cert-expire.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/sh

file=${1:-'hosts_check.txt'}
workdir=`dirname $0`

if [ ! -f "$workdir/$file" ];then
echo "当前目录不存在文件: $1"
else
cat $workdir/$file | while read LINE
do
{
host=`echo $LINE|awk '{print $1}'`
port=`echo $LINE|awk '{print $2}'`
port=${port:-'443'}
token=`echo $LINE|awk '{print $3}'`
if [ ! $token ]; then
token='01a48c1**033a9ab6**********22ca67d**f7e0291ef4f'
fi
day=`$workdir/check-cert-expire-host.sh $host $port`
if [[ $day -lt 10 && $day -ge 1 ]]; then
echo "[${host}] SSL证书还有$day天过期,请注意续期"
curl 'https://oapi.dingtalk.com/robot/send?access_token='"${token}" -H 'Content-Type: application/json' -d '{"msgtype": "text","text": {"content": "'"[${host}] SSL证书还有$day天过期,请注意续期"'"}}'
fi
if [[ $day -le 0 ]]; then
echo "[${host}] SSL证书已过期,请安排续期"
curl 'https://oapi.dingtalk.com/robot/send?access_token='"${token}" -H 'Content-Type: application/json' -d '{"msgtype": "text","text": {"content": "'"[${host}] SSL证书已过期,请安排续期"'"}}'
fi
} &
wait
done
fi


hosts_check.txt文件格式
[域名] [端口] [ding_token]
其中域名是必须的,每行一条记录
例如:
www.baidu.com 443 01a48c1033a9ab6**22ca67d**f7e0291ef4f

加入计划任务

1
2
#每天10点执行检测
0 10 * * * /root/script/check-cert-expire.sh