服务证书到期需要更新,但如果更新滞后,会导致服务停用,所以需要监测证书的到期时间,提前几天通知相关同事及时更新证书,废话不说,直接上代码
用于存放各类变量,函数之类如:
import traceback
import requests
url_list = ['https://www.baidu.com','https://www.google.com']#保存待检测的网站地址,用于获取证书信息
def DingDingalert(msg):
"""
send alert info by DingDing
:param msg:
:return:
"""
data = {
'msgtype': 'text',
'text': {
"content": msg
},
}
try:
#新建钉钉群,添加机器人,拿到webhook信息
return requests.post(
"https://oapi.dingtalk.com/robot/send?access_token"
"=sssssssssssssssss",
json=data)
except:
traceback.print_exc()
# -*- coding:utf-8 -*-
import re
import subprocess
from datetime import datetime
from settings import url_list, DingDingalert
for url in url_list:
comm = "curl -Ivs " + url + "--connect-timeout 10"#获取证书各类信息,其中就有expire date
result = subprocess.getstatusoutput(comm)#这个方法Python2不支持,得用Python3
with open('result.txt', 'w') as f:#将curl结果写入TXT文件,为了方便提取信息,用‘w'模式,保证每次执行都会覆盖原来内容
f.write(str(result[1]))
with open('result.txt') as f:
for line in f:
res = re.findall('expire date: (.*?) GMT', line)#通过正则表达式获取expire date信息
if len(res) != 0:#因为是按行读取,所以只有返回的信息长度不为0,才是拿到了expire date
expire_date = res[0].split(', ')[1]#服务器运行脚本返回的是类似:Tue,10 Apr 2021 09:50:59,故只取逗号后面的日期信息即可
break#拿到日期信息就跳出循环了
else:
print("没有expire date信息")
print(expire_date)
expire_date = datetime.strptime(expire_date, "%d %b %Y %H:%M:%S")#将字符串格式的日期信息转换为datetime格式
remain_day = (expire_date - datetime.now()).days#获取剩余有效天数,到期日期减去当日日期
print(remain_day)
if remain_day <= 3:#当剩余有效天数小于3天时,钉钉报警通知,可以自己定义几天
msg = url + " certificate will expire in {} days".format(remain_day)
print(msg)
DingDingalert(msg)
else:
msg = url + " certificate will expire in {} days".format(remain_day)
print(msg)
#DingDingalert(msg)
1.4 服务器部署脚本,并设置定时任务
服务器环境:Python3
定时任务设置:crontab -e
9 2 * * * /usr/bin/python3 /root/certificate_check/certificate-check.py
( 每天2点9分执行一次脚本,可按需要设置频率,服务器在国外的话需考虑和国内时差数来设置)