一、脚本思路
1.openssl s_client 获取证书有效期
2.将相关时间做时间戳转换,转换成天数
3. 调用钉钉群组机器人做证书有效期预警
# cat ssl_validity_alarm.sh
#############################################################
#!/bin/bash
# 加载环境变量
. /etc/profile
. ~/.bash_profile
. /etc/bashrc
# 被检测的域名和端口
domain_name="www.example.com"
domain_port="443"
advance_warning_days="300"
# 获取脚本所在目录、脚本名称
script_dir=$( cd "$( dirname "$0" )" && pwd )
script_name=$(basename ${0})
# 钉钉群组机器人地址
robot_webhook_url="https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxx"
# 创建钉钉机器人告警函数
send_robot_warning() {
curl -X POST "${robot_webhook_url}" \
-H 'Content-Type: application/json' \
-d ' {"msgtype": "text", "text": {"content": "'"$1"'"}}'
}
# 用openssl获取域名的证书到期日期
cert_end_time=$(echo | openssl s_client -servername ${domain_name} -connect ${domain_name}:${domain_port} 2>/dev/null | openssl x509 -noout -dates |grep 'After'| awk -F '=' '{print $2}'| awk -F ' +' '{print $1,$2,$4 }' )
# 将证书到期日期转化为时间戳
cert_end_timestamp=$(date +%s -d "$cert_end_time")
# 将当前日期转化为时间戳
now_timestamp=$(date +%s -d "$(date "+%Y-%m-%d %H:%M:%S")")
# 到期时间减去目前时间,再转化为天数
rest_time=$(($(($cert_end_timestamp - $now_timestamp))/(60*60*24)))
echo "证书有效天数剩余:${rest_time}"
if [ "${rest_time}" -lt "${advance_warning_days}" ];then
send_robot_warning "${domain_name} SSL证书有效期少于${advance_warning_days}天,存在过期风险,请关注!"
fi
#############################################################
二、钉钉群组机器人创建注意事项
1. 开启消息推送
2. 设置自定义关键字,而且发送消息中必须包含自定义关键字
3.不要设置加签
三、脚本测试
# sh ssl_validity_alarm.sh
四、参考
OpenSSL s_client 获取keytool证书和openSSLl证书
https://www.jianshu.com/p/09773dc15cbc
OpenSSL Command-Line
https://www.madboa.com/geek/openssl/#cert-retrieve
用shell脚本监控https证书到期时间
https://blog.slogra.com/post-772.html
https://www.dgstack.cn/archives/3227.html
https://blog.csdn.net/weixin_43876317/article/details/109044133
钉钉开放平台文档
https://open.dingtalk.com
https://www.alibabacloud.com/help/zh/doc-detail/108367.htm
https://developers.dingtalk.com/document/app/document-upgrade-notice#/serverapi2/qf2nxq
云之家群组机器人开发者文档
https://open.yunzhijia.com/gitbook-wiki/server-api/im-robot.html
使用certbot-auto申请Let’s Encrypt Wildcard证书
https://blog.slogra.com/post-746.html
PythonN实现钉钉发送报警消息
https://www.freesion.com/article/5057722191
使用python检查SSL证书到期情况
https://python.01314.cn/201812519.html