脚本监控域名证书有效期,超过60天邮件通知
脚本路径:
/opt/domain_script
-check_public_domain_ssl.py
-check_ssl_data #域名证书检查结果文件目录
-domain_datasource #扫描域名列表目录
-logs #记录日志
]$ cat /opt/domain_script/domain_datasource/public_domain_list
www.baidu.com
...
脚本:
#!/bin/python
#-- coding:UTF-8 --
import smtplib
import os
from datetime import datetime
from datetime import date
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# date format
current_time = date.today().strftime('%Y-%m-%d')
#local file env
internal_domain_list = '/opt/domain_script/domain_datasource/internal_domain_list'
domain_check_result = '/opt/domain_script/check_ssl_data/internal_domain_check_result.csv'
domain_checK_log = '/opt/domain_script/logs/internal_domain_check.log'
#mail notification
smtp_host = '10.0.0.1'
sendfrom = '[email protected]'
alertmaillist = ['[email protected]']
ccmaillist = []
def generate_html_mail(all_domain_check_result):
html_result = ""
for per_row_domain in all_domain_check_result:
per_html_tr = '''
<tr>
<td> {} </td>
<td> {} </td>
<td> {} </td>
<td> {} </td>
</tr>
'''.format(per_row_domain[0],per_row_domain[1],per_row_domain[2],per_row_domain[3])
html_result = html_result + per_html_tr
message_css = """
<style>
#customers {
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 80%;
}
#customers td, #customers th {
border: 1px solid #ddd;
padding: 8px;
}
#customers tr:nth-child(even){background-color: #f2f2f2;}
#customers tr:hover {background-color: #ddd;}
#customers th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: rgb(63,63,63);
color: white;
font-size: 14px;
}
#customers td {
font-size: 12px;
text-align: left;
}
</style>
"""
message = """
%s
<p>Dear all,</p>
<p></p>
<p>Your monitoring domain name certificate is about to expire or has already expired.</p>
<p></p>
<table id="customers">
<tbody>
<tr>
<th>Domain</th>
<th>Common Name</th>
<th>SSL Expire Time</th>
<th>Expiration Days</th>
</tr>
%s
</tbody>
</table>
<br />
<br />
<hr>
<p>
Note: Please update the certificates for the monitoring domain names mentioned above in a timely manner to prevent certificate expiration.
</p>
<br>
"""%(message_css,html_result)
return message
def sendmail(all_domain_check_result):
'''send alert mail'''
try:
title = '[Internal Domain] Domain Certificate Expiration Alarm'
if len(all_domain_check_result) > 0:
content = generate_html_mail(all_domain_check_result)
else:
content = 'Dear all \n' + ' All internal domain name certificates are within their validity period. Please be informed. Thank you.\n'
message = MIMEMultipart()
msg_content = MIMEText(content, 'html', 'utf-8')
message.attach(msg_content)
message['Subject'] = title
message['From'] = sendfrom
message['To'] = ','.join(alertmaillist)
message['Cc'] = ','.join(ccmaillist)
att1 = MIMEText(open(domain_check_result, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="Certificate_Expire_List.csv"'
message.attach(att1)
smtpObj = smtplib.SMTP()
smtpObj.connect(smtp_host, 25)
smtpObj.sendmail(
sendfrom, alertmaillist + ccmaillist, message.as_string())
smtpObj.quit()
print('Alert Mail send success')
except smtplib.SMTPException as e:
print('Alert Mail send error', e)
def get_domain_list():
"""
获取需要监控的域名列表
"""
with open(internal_domain_list, mode='rt') as f:
domain_pool = []
for line in f:
per_domain_list = []
r_line = line.split()
per_domain = r_line[0]
per_domain_expire_time = r_line[1]
per_domain_list.append(per_domain)
per_domain_list.append(per_domain_expire_time.replace('\n',''))
domain_pool.append(per_domain_list)
return domain_pool
def get_diff_days(start_date, end_date):
"""
获取两个时间对象的时间差天数
"""
if start_date and end_date:
delta = datetime.strptime(end_date, "%Y-%m-%d") - datetime.strptime(start_date, "%Y-%m-%d")
return delta.days
else:
return 0
def get_ssl_cert(domainlist):
"""
通过socket获取整数信息
"""
per_domain_check_info = []
try:
expire_days = get_diff_days(current_time,domainlist[1])
if 'cneb' in domainlist[0]:
common_name = '*.cneb' + domainlist[0].split('cneb')[1]
else:
common_name = domainlist[0]
per_domain_check_info.append(domainlist[0])
per_domain_check_info.append(common_name)
per_domain_check_info.append(domainlist[1])
per_domain_check_info.append(expire_days)
except Exception as e:
err = e.__str__()
log_info = 'Domain:[%s] Msg: [socket.timeout: timed out]'%(domainlist[0])
domain_check_log(log_info)
per_domain_check_info.append(domainlist[0])
per_domain_check_info.append('Null')
per_domain_check_info.append(None)
per_domain_check_info.append(0)
return per_domain_check_info
def domain_check_log(loginfo):
"""
写日志到本地
"""
with open(domain_checK_log, mode='a+') as f:
log_date = datetime.now()
f.write('%s %s \n'%(log_date,loginfo))
def write_excel(data):
"""
把证书信息写到excel表中,后续邮件发送
"""
with open(domain_check_result, mode='a+') as f:
f.write(data)
def export_ssl_check_result(all_check_list):
"""
把获取的证书信息写入表格中
"""
write_excel('Domain,Common Name,SSL Expire Time,Expire_days\n')
for per_ssl_check_result in all_check_list:
#[u'wxbk.sephora.cn', u'sephora.cn', '2022-09-14', '2023-10-13', 28]
datamsg = '%s,%s,%s,%s, \n'%(per_ssl_check_result[0],per_ssl_check_result[1],per_ssl_check_result[2],per_ssl_check_result[3])
print(datamsg)
write_excel(datamsg)
if __name__ == '__main__':
internal_domain_poll = get_domain_list()
all_domain_check_result = []
for per_domain in internal_domain_poll:
per_check_ssl_result = get_ssl_cert(per_domain)
if per_check_ssl_result[3] <= 60:
all_domain_check_result.append(per_check_ssl_result)
if os.path.exists(domain_check_result):
os.remove(domain_check_result)
if len(all_domain_check_result) > 0:
export_ssl_check_result(all_domain_check_result)
sendmail(all_domain_check_result)
执行脚本:
~]# python3 check_public_domain_ssl.py