import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from ping3 import ping
import time
from datetime import datetime
import threading
import tkinter as tk
from tkinter import messagebox, filedialog
import json
try:
print("连接到SMTP服务器...")
server = smtplib.SMTP_SSL(smtp_server, smtp_port)
server.login(smtp_user, smtp_password)
print("发送邮件...")
text = msg.as_string()
server.sendmail(from_email, to_emails, text)
server.quit()
print("邮件发送成功。")
except Exception as e:
print(f"发送邮件失败: {e}")
messagebox.showerror("邮件发送失败", f"发送邮件失败: {e}")
def monitor_ping(hosts, timeout, check_interval, email_details):
host_status = {host['address']: True for host in hosts}
while True:
for host in hosts:
address = host['address']
remark = host['remark']
try:
print(f"正在检测主机({remark})...")
response = ping(address, timeout=timeout)
if response is None:
if host_status[address]:
print(f"主机({remark}) 断开,发送告警邮件...")
subject = f"告警: ({remark}) 已断开"
body = f"主机 {address} ({remark}) 已断开连接\n断网时间为: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
send_email(subject, body, **email_details)
host_status[address] = False
else:
if not host_status[address]:
print(f"主机({remark}) 已恢复,发送恢复邮件...")
subject = f"恢复: ({remark}) 已恢复"
body = f"主机 {address} ({remark}) 已恢复响应连接\n恢复时间为: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
send_email(subject, body, **email_details)
host_status[address] = True
print(f"主机({remark}) 可达,响应时间: {response} ms")
except Exception as e:
print(f"ping过程中出错: {e}")
messagebox.showerror("ping出错", f"ping过程中出错: {e}")
time.sleep(check_interval)
def start_monitoring():
try:
to_emails = [email.strip() for email in to_email_entry.get().split(",") if email.strip()]
email_details = {
'to_emails': to_emails,
'from_email': from_email_entry.get(),
'smtp_server': smtp_server_entry.get(),
'smtp_port': int(smtp_port_entry.get()),
'smtp_user': smtp_user_entry.get(),
'smtp_password': smtp_password_entry.get()
}
hosts = []
for i in range(len(host_entries)):
if host_entries:
address = host_entries.get()
remark = remark_entries.get()
if address and remark:
hosts.append({'address': address, 'remark': remark})
if not email_details['to_emails'] or not email_details['from_email'] or not email_details['smtp_server'] or not email_details['smtp_user'] or not email_details['smtp_password']:
raise ValueError("所有邮件配置项必须填写完整")
def delete_host_entry(row):
index = row - 8
if 0 <= index < len(host_entries):
host_entries[index].grid_forget()
host_entries[index].destroy() # 销毁主机输入框
remark_entries[index].grid_forget()
remark_entries[index].destroy() # 销毁备注输入框
delete_buttons[index].grid_forget()
delete_buttons[index].destroy() # 销毁删除按钮
# 重建列表,剔除已经销毁的项
host_entries[:] = [entry for entry in host_entries if entry.winfo_exists()]
remark_entries[:] = [entry for entry in remark_entries if entry.winfo_exists()]
delete_buttons[:] = [button for button in delete_buttons if button.winfo_exists()]
update_layout()
def update_layout():
for i in range(len(host_entries)):
host_entries.grid(row=i + 8, column=1, padx=5, pady=5, sticky="ew")
remark_entries.grid(row=i + 8, column=2, padx=5, pady=5, sticky="ew")
delete_buttons.grid(row=i + 8, column=3, padx=5, pady=5, sticky="ew")
for entry in host_entries:
entry.grid_forget()
entry.destroy()
for entry in remark_entries:
entry.grid_forget()
entry.destroy()
for button in delete_buttons:
button.grid_forget()
button.destroy()