美文网首页
python3下检查ssl证书过期时间并邮件通知

python3下检查ssl证书过期时间并邮件通知

作者: Xpitz | 来源:发表于2019-03-18 17:38 被阅读0次

    欢迎关注我的微信公众号:「阿拉平平」

    安装模块

    # ssl模块
    pip install pyopenssl
    
    # 邮件模块
    pip install yagmail
    

    域名文件

    # cat /data/scripts/ssl_check/domain.txt
    
    www.baidu.com 百度
    www.sohu.com 搜狐
    

    脚本代码

    #!/usr/bin/env python3
    # -*- coding:utf-8 -*-
    
    from urllib3.contrib import pyopenssl as reqs
    from datetime import datetime
    import yagmail
    
    
    # 读取域名文件
    def get_domain_list():
        obj_list = []
        with open('/data/scripts/ssl_check/domain.txt') as f:
            for i in f:
                obj_list.append({'domain': i.split()[0], 'tag': i.split()[1]})
        return obj_list
    
    # 调用openssl,获取过期时间
    def get_expire_time(url):
        x509 = reqs.OpenSSL.crypto.load_certificate(reqs.OpenSSL.crypto.FILETYPE_PEM, reqs.ssl.get_server_certificate((url, 443)))
        return datetime.strptime(x509.get_notAfter().decode()[0:-1], '%Y%m%d%H%M%S')
    
    # 发送邮件
    def send_mail(expire_list):
        user = 'your-email@email.com'
        password = 'your-password'
        # qq邮箱
        host = 'smtp.exmail.qq.com'
        to = 'your-revevier@email.com'
        subject = 'ssl证书过期告警'
        d = ''
        for i in expire_list:
            d += '''\
      <tr>
        <td align="center">''' + str(i['domain']) + '''</td>
        <td align="center">''' + str(i['remain']) + '''</td>
        <td align="center">''' + str(i['tag']) + '''</td>
      </tr>
    '''
        html = '''\
    <table width="70%" border="1" bordercolor="black" cellspacing="0" cellpadding="0">
      <tr>
        <td width="140" align="center" ><strong>域名</strong></td>
        <td width="110" align="center" ><strong>剩余天数</strong></td>
        <td width="110" align="center" ><strong>所属项目</strong></td>
      </tr>
    '''+ d +'''</table>'''
        # 去除邮件中多余换行
        html = html.replace("\n", "")
        yag = yagmail.SMTP(user = user, password = password, host = host)
        yag.send(to = to, subject = subject, contents = html)
    
    if __name__ == '__main__':
        check_days = 15
        domain_list = get_domain_list()
    
        for i in domain_list:
            remain_days = (get_expire_time(i['domain']) - datetime.now()).days
            i['remain'] = remain_days
    
        expire_domain_list = [i for i in domain_list if i['remain'] <= check_days]
    
        if (len(expire_domain_list) != 0):
            send_mail(expire_domain_list)
    

    注意:

    • send_mail函数中要修改邮箱信息。
    • 可按照实际情况修改check_days的大小。

    定时任务

    # crontab -e
    
    0 2 * * 0 python3 /data/scripts/ssl_check/check.py
    

    这里我设置每周执行脚本一次,可按照实际情况自行设置。


    写在后面

    相关文章

      网友评论

          本文标题:python3下检查ssl证书过期时间并邮件通知

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