美文网首页
用 python 编写简单的证书域名到期报警脚本

用 python 编写简单的证书域名到期报警脚本

作者: 李方成 | 来源:发表于2018-07-16 14:58 被阅读0次

    将脚本放在服务器的计划任务内,定时检测,证书到期不足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 datetime
    from email.mime.text import MIMEText
    from email.header import Header
    from smtplib import SMTP
    import requests
    import json
    
    host_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 text
    
    
    text = 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.content
    
    
    def 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()
    

    相关文章

      网友评论

          本文标题:用 python 编写简单的证书域名到期报警脚本

          本文链接:https://www.haomeiwen.com/subject/bdlbpftx.html