欢迎关注我的微信公众号:「阿拉平平」
安装模块
# 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
这里我设置每周执行脚本一次,可按照实际情况自行设置。
写在后面
- 脚本使用
pyopenssl
时有部分参考了这篇文章:
https://www.itnotebooks.com/?p=768 -
yagmail
是一个非常好用的发送邮件模块。我编写脚本时发现一个问题:发送html格式的内容会带来多余的空行,所以需要额外处理下。附上模块的github地址:https://github.com/kootenpv/yagmail
网友评论