指令碼監控域名證書有效期,超過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 = 'NoReply@alibaba.com'
alertmaillist = ['suixin7888@163.com']
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