tools,python SSL证书告警 发表于 2022-05-07 浏览量 538 没有评论 # 背景 ssl证书一般都是邮件告警,但是,作为运维管理员,每天都会收到大量的邮件,有可能会错过ssl证书提示的邮件,于是,脑洞大开,使用腾讯自带的API,获取全部ssl证书的信息,然后过滤出自己想要的信息,比如说申请日期,到期日期等,算出当前域名的ssl证书还有多少天,并发送到飞书群。 # 安装腾讯sdk ``` pip3 install --upgrade tencentcloud-sdk-pytho ``` # 脚本 ``` import json import time import requests import datetime as dt from tencentcloud.common import credential from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.ssl.v20191205 import ssl_client, models def send_message(color,content): title = 'ssl证书' robot_id = '9c612557-7875-4000-94cc-31924xxxx' # 这个飞书群的ID webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/%s" % robot_id header = { "Content-Type": "application/json", "Charset": "UTF-8" } post_data = { "msg_type": "interactive", "card": { "config": { "wide_screen_mode": True, "enable_forward": True }, "elements": [ { "tag": "div", "text": { "content": content, "tag": "lark_md" }, } ], "header": { "title": { "content": title, "tag": "plain_text" }, "template": color } } } post_data_json = json.dumps(post_data) info = requests.post(url=webhook, data=post_data_json, headers=header) print(info) try: cred = credential.Credential("xxx", "xxx") # 腾讯云的账号的秘钥 httpProfile = HttpProfile() httpProfile.endpoint = "ssl.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ssl_client.SslClient(cred, "", clientProfile) req = models.DescribeCertificatesRequest() params = { } req.from_json_string(json.dumps(params)) resp = client.DescribeCertificates(req) domain = json.loads(resp.to_json_string()) infos = domain['Certificates'] today = time.strftime("%Y-%m-%d", time.localtime()) dt1 = dt.datetime.strptime(today, "%Y-%m-%d") for i in infos: end = (i['CertEndTime']).split(" ")[0] domain = i['Domain'] dt2 = dt.datetime.strptime(end, "%Y-%m-%d") sub_day = (dt2 - dt1).days if sub_day < 60: send_message(domain,sub_day) content = "域名:" + domain + "\t" + "证书剩余天数:" + str(sub_day) + "天" color = 'red' send_message(color,content) elif sub_day > 60: content = "域名:" + domain + "\t" + "证书剩余天数:" + str(sub_day) + "天" color = 'green' send_message(color,content) # print("证书剩余日期:" + str(sub_day) + "天") # print("域名:" + i['Domain']+ ",证书申请日期:" + i['CertBeginTime'] + ",证书到期时间:" + i['CertEndTime']) except TencentCloudSDKException as err: print(err) ``` - python代码能力不咋样,能写出来就很不错了,大神请忽略,哈哈哈!