import socket
import ssl
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
import xlsxwriter
# Author: ran
# 获取域名SSL证书到期时间
def get_ssl_expiry_date(domain, port=443):
context = ssl.create_default_context()
with socket.create_connection((domain, port)) as sock:
with context.wrap_socket(sock, server_hostname=domain) as ssl_sock:
cert = ssl_sock.getpeercert()
expiry_date = datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
return expiry_date
# 计算证书剩余天数
def get_days_until_expiry(expiry_date):
return (expiry_date - datetime.now()).days
# 检查多个域名的SSL证书到期时间,并生成Excel文件
def check_ssl_expiry(domains, excel_path):
data = []
for domain in domains:
try:
expiry_date = get_ssl_expiry_date(domain)
days_left = get_days_until_expiry(expiry_date)
status = "正常" if days_left >= 15 else "即将到期" if days_left >= 0 else "已过期"
data.append([domain, expiry_date.strftime('%Y-%m-%d %H:%M:%S'), days_left, status])
except Exception as e:
data.append([domain, "无法获取证书信息", "N/A", f"错误: {e}"])
# 创建Excel文件
with xlsxwriter.Workbook(excel_path) as workbook:
worksheet = workbook.add_worksheet("SSL到期状态")
headers = ["域名", "证书到期时间", "剩余天数", "状态"]
worksheet.write_row(0, 0, headers)
for row_num, row_data in enumerate(data, start=1):
worksheet.write_row(row_num, 0, row_data)
return data
# 发送带附件的邮件
def send_email(smtp_config, subject, body, attachment_path):
msg = MIMEMultipart()
msg['From'] = f"{smtp_config['from_name']} <{smtp_config['from_email']}>"
msg['To'] = f"{smtp_config['to_name']} <{smtp_config['to_email']}>"
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(body, 'plain', 'utf-8'))
# 添加附件
with open(attachment_path, 'rb') as file:
part = MIMEBase('application', 'octet-stream')
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header(
'Content-Disposition',
f'attachment; filename="{attachment_path.split("/")[-1]}"'
)
msg.attach(part)
# 发送邮件
try:
with smtplib.SMTP_SSL(smtp_config['smtp_server'], smtp_config['smtp_port']) as server:
server.login(smtp_config['smtp_user'], smtp_config['smtp_password'])
server.sendmail(smtp_config['from_email'], smtp_config['to_email'], msg.as_string())
print("邮件发送成功!")
except Exception as e:
print(f"邮件发送失败: {e}")
# 主函数
if __name__ == "__main__":
domains = [
"www.baidu.com",
"www.google.com",
]
# SMTP配置
smtp_config = {
"smtp_server": "smtp.163.com",
"smtp_port": 465,
"smtp_user": "stmp账号",
"smtp_password": "授权码",
"from_email": "发信人",
"from_name": "SSL监控",
"to_email": "接收文件",
"to_name": "管理员",
}
# Excel文件路径
excel_path = "/tmp/ssl_status.xlsx"
# 检查SSL状态并生成Excel
ssl_data = check_ssl_expiry(domains, excel_path)
# 准备邮件内容
expiring_domains = [row[0] for row in ssl_data if row[3] == "即将到期"]
body = "以下是SSL证书检查结果:\n\n"
body += "\n".join([f"域名: {row[0]}, 到期时间: {row[1]}, 剩余天数: {row[2]}" for row in ssl_data])
if expiring_domains:
body += f"\n\n注意: 以下域名的SSL证书即将到期:\n{', '.join(expiring_domains)}"
# 发送邮件
send_email(smtp_config, "SSL证书到期提醒", body, excel_path)
# 删除附件
if os.path.exists(excel_path):
os.remove(excel_path)
print(f"附件 {excel_path} 已删除。")
增加了stmp邮件通知和表格附件发送
评论 (0)