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

2019-03-18  本文已影响0人  Xpitz

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

安装模块

# 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)

注意:

定时任务

# crontab -e

0 2 * * 0 python3 /data/scripts/ssl_check/check.py

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


写在后面

上一篇下一篇

猜你喜欢

热点阅读