用 python 编写简单的证书域名到期报警脚本
将脚本放在服务器的计划任务内,定时检测,证书到期不足60天发送报警邮件及钉钉提醒。
在服务器上需要提前安装好 requests 库。 pip install requests
钉钉机器人
https://open-doc.dingtalk.com/docs/doc.htm?treeId=257&articleId=105735&docType=1
脚本
#!/usr/bin/env python# -*- coding: utf-8 -*-from datetime import datetimefrom email.mime.text import MIMETextfrom email.header import Headerfrom smtplib import SMTPimport requestsimport jsonhost_server = 'mail.abc.com'sender = 'lifangcheng@abc.com'passwd = 'xxxxx'sender_mail = 'lifangcheng@abc.com'receiver = 'group@abc.com'dingding_url = 'https://https://oapi.dingtalk.com/robot/send?access_token=a23dd21319a3d24ff0e1839a17e0d44197abeb58858c1ed9a94484361xxxxxx'headers = {'Content-Type': 'application/json; charset=utf-8'}server_list = [{'host': '*.open.abc.com', 'expire_time': '2020-05-26'}, {'host': '*.abc.com', 'expire_time': '2020-05-26'}, {'host': '*.x.abc.com', 'expire_time': '2020-05-26'}, {'host': 'test.abc.net', 'expire_time': '2020-05-09'}]def echo_remaining_time(server_list): text = '' for server in server_list: now = datetime.now() expire_time = datetime.strptime(server['expire_time'], '%Y-%m-%d') diff = expire_time - now if int(diff.days) < 60: text = text + '证书名称: ' + server['host'] \ + ' ' + '剩余日期:' + str(diff.days) + '天' + '\n' return texttext = echo_remaining_time(server_list)post_data = { 'msgtype': 'text', 'text': { 'content': text }, 'at': { 'isAtAll': True }}r = requests.post(dingding_url, headers=headers, data=json.dumps(post_data))print r.contentdef send_mail(): mail_content = echo_remaining_time(server_list) mail_title = '重要:阿里云证书到期提醒!!!' if mail_content: smtp = SMTP(host_server) # smtp.set_debuglevel(1) smtp.ehlo(host_server) smtp.login(sender, passwd) msg = MIMEText(mail_content, 'plain', 'utf-8') msg['Subject'] = Header(mail_title, 'utf-8') msg['From'] = sender_mail msg['To'] = receiver smtp.sendmail(sender_mail, receiver, msg.as_string())if __name__ == '__main__': send_mail()
赞 (0)