监听:
watchDir.py
import os
import time
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_email(sender, password, recipients, subject, content):
# 发送邮件函数,需要传入发件人、密码、收件人、主题和正文内容
try:
smtp_server = 'smtp.qq.com'
smtp_port = 465 # QQ邮箱SMTP端口为465
sender_mail = '407194145@qq.com' # 发件人邮箱
password = 'kstbbetobypbbjjj' # qq邮箱POP3/IMAP/SMTP/Exchange/CardDAV 服务授权码
receivers_mail = '2388537724@qq.com' # 收件人邮箱,可以是多个,用逗号隔开
message = MIMEText(content, 'plain', 'utf-8')
message['From'] = '407194145@qq.com' # 设置发件人
message['To'] = Header(receivers_mail, 'utf-8') # 设置收件人
message['Subject'] = Header(subject, 'utf-8') # 设置主题
smtpObj = smtplib.SMTP_SSL(smtp_server, smtp_port)
smtpObj.login(sender_mail, password)
smtpObj.sendmail(sender_mail, receivers_mail.split(','), message.as_string())
print("邮件发送完成")
except Exception as e:
print("邮件发送失败:", e)
def monitor_folder(folder_path, sender, password, recipients, subject):
"""
监控目录变化并发送报警邮件
:param folder_path: 监控的目录路径
:param sender: 发送邮件的邮箱地址
:param password: 发送邮件的邮箱密码
:param recipients: 收件人邮箱地址,可以是多个,用逗号隔开
:param subject: 邮件主题
"""
file_dict = {} # 用于存储监控目录中已经出现过的文件名和对应修改时间戳
while True:
time.sleep(10) # 每次间隔10秒进行监测,可以根据实际情况调整
for file_name in os.listdir(folder_path):
if not file_name.endswith('.txt'):
continue
file_path = os.path.join(folder_path, file_name)
timestamp = os.stat(file_path).st_mtime
if file_path not in file_dict:
# 如果文件新出现,则记录文件名和修改时间戳
file_dict[file_path] = timestamp
with open(file_path, encoding='utf-8') as f:
content = f.read()
send_email(sender, password, recipients, subject, content)
else:
# 如果文件已存在,但修改时间戳发生变化,则说明文件发生了修改
if file_dict[file_path] != timestamp:
file_dict[file_path] = timestamp
with open(file_path, encoding='utf-8') as f:
content = f.read()
send_email(sender, password, recipients, subject, content)
if __name__ == '__main__':
folder_path = 'D:/pythonTest/neoTime' # 生成文件的路径
sender = '407194145@qq.com'
password = 'kstbbetobypbbjjj'
recipients = '2388537724@qq.com'
subject = '文件监控报警邮件'
monitor_folder(folder_path, sender, password, recipients, subject)
发送邮件:
monitor
import os
import time
import psutil
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
def send_email(sender, password, recipients, subject, content, attachments):
# 发送邮件函数,需要传入发件人、密码、收件人、主题和正文内容
try:
smtp_server = 'smtp.qq.com'
smtp_port = 465 # QQ邮箱SMTP端口为465
sender_mail = '407194145@qq.com' # 发件人邮箱
password = 'kstbbetobypbbjjj' # qq邮箱POP3/IMAP/SMTP/Exchange/CardDAV 服务授权码
receivers_mail = '2388537724@qq.com' # 收件人邮箱,可以是多个,用逗号隔开
msg = MIMEMultipart() # 创建MIMEMultipart对象
msg.attach(MIMEText(content, 'plain', 'utf-8')) # 添加正文内容
for attachment in attachments:
with open(attachment, 'rb') as f:
data = f.read()
att = MIMEText(data, 'base64', 'utf-8')
att['Content-Type'] = 'application/octet-stream' # 定义文件格式类型
att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment)) # 设置附件名称
msg.attach(att) # 将附件添加到邮件中
msg['From'] = '407194145@qq.com' # 设置发件人
msg['To'] = Header(receivers_mail, 'utf-8') # 设置收件人
msg['Subject'] = Header(subject, 'utf-8') # 设置主题
smtpObj = smtplib.SMTP_SSL(smtp_server, smtp_port)
smtpObj.login(sender_mail, password)
smtpObj.sendmail(sender_mail, receivers_mail.split(','), msg.as_bytes()) # 发送邮件
print("邮件发送完成")
except Exception as e:
print("邮件发送失败:", e)
def generate_log_file(log_path):
# 生成日志文件,记录系统状态信息
with open(log_path, 'a+', encoding='utf-8') as f:
f.write("======================" + time.strftime("%Y-%m-%d", time.localtime()) + "======================\n")
f.write("CPU使用率:%s%%" % psutil.cpu_percent(interval=1.0) + "\n") #写入cpu使用情况
f.write("内存使用率:%s%%" % psutil.virtual_memory().percent + "\n") #写入内存使用情况
for disk in psutil.disk_partitions():
if os.name == 'nt':
if 'cdrom' in disk.opts or disk.fstype == '':
continue
f.write("盘符 %s 磁盘使用率:%s%%" % (disk.device, psutil.disk_usage(disk.mountpoint).percent) + "\n") #写入内存使用情况
f.write("\n\n")
def generate_txt_file(txt_path):
# 生成txt格式文件,记录系统状态信息
txt_content = []
txt_content.append(time.strftime("%Y-%m-%d", time.localtime())) #获取时间作于文件名
txt_content.append("CPU使用率:%s%%" % psutil.cpu_percent(interval=1.0)) #获取cpu使用情况
txt_content.append("内存使用率:%s%%" % psutil.virtual_memory().percent) #获取内存使用情况
for disk in psutil.disk_partitions():
if os.name == 'nt':
if 'cdrom' in disk.opts or disk.fstype == '':
continue
txt_content.append("盘符 %s 磁盘使用率:%s%%" % (disk.device, psutil.disk_usage(disk.mountpoint).percent))#获取磁盘使用情况
with open(txt_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(txt_content)) #写入文本cpu等情况
# print(txt_path)
def monitor_system(sender, password, recipients, subject, log_path, txt_path):
"""
监控系统资源并发送邮件报警
:param sender: 发送邮件的邮箱地址
:param password: 发送邮件的邮箱密码
:param recipients: 收件人邮箱地址,可以是多个,用逗号隔开
:param subject: 邮件主题
:param log_path: 日志文件保存路径
:param txt_path: txt格式文件保存路径
"""
while True:
#休眠10秒
time.sleep(10)
# 监听cpu使用率
cpu = psutil.cpu_percent(interval=1)
stCpu = "当前cpu使用率{}%".format(cpu)
# 监听内存使用率
memory = psutil.virtual_memory()
memory = memory.percent
strMemory = "当前内存占使用率{}%".format(memory)
# 监听磁盘使用率
disk = psutil.disk_usage("C:/")
disk = disk.percent
strDisk = "当前磁盘使用率{}%".format(disk)
time.sleep(3)
while True:
if cpu >= cpu_threshold or memory >= mem_threshold or disk >= io_threshold:
with open(txt_path, "w", encoding="utf-8") as f: # 指定路径保存txt文件
if cpu >= 80:
print("添加cpu")
f.write(stCpu)
if memory >= 80:
print("添加内存")
f.write(strMemory)
if disk >= 80:
print("添加磁盘信息")
f.write(strDisk)
with open(log_path, "w", encoding="utf-8") as f: # 指定路径保存日志文件
f.write(stCpu)
f.write(strMemory)
f.write(strDisk + "\n")
if cpu > cpu_threshold or memory > mem_threshold or disk > io_threshold:
# 如果系统运行状态超过阈值,则生成日志文件并发送到指定邮箱
generate_log_file(log_path)
send_email(sender, password, recipients, subject, "请查看附件中的日志文件", [log_path])
# 生成txt格式文件并保存到目录A
generate_txt_file(txt_path)
print("已生成txt格式文件:", txt_path)
if __name__ == '__main__':
sender = '407194145@qq.com'
password = 'kstbbetobypbbjjj'
recipients = '2388537724@qq.com'
subject = '系统监控报警邮件'
log_path = r'D:/pythonTest/neoTime/log.log' #日志位置
txt_path = os.path.join(r'D:/pythonTest/neoTime', time.strftime("%Y%m%d", time.localtime()) + ".txt")
cpu_threshold = 80
mem_threshold = 80
io_threshold = 80
monitor_system(sender, password, recipients, subject, log_path, txt_path)