监控文件夹大小变化并发送邮件通知
脚本内容如下
import os
import time
import smtplib
from email.mime.text import MIMEText
# 设置要监控的目录路径
MONITOR_DIR = '/path/to/monitor/dir'
# 设置发送邮件的参数
SENDER = 'your_email@example.com'
RECIPIENT = 'recipient@example.com'
SMTP_SERVER = 'smtp.example.com'
SMTP_PORT = 587
SMTP_USERNAME = 'your_username'
SMTP_PASSWORD = 'your_password'
def get_dir_size(dir_path):
"""获取目录大小(以字节为单位)"""
total_size = 0
for dirpath, dirnames, filenames in os.walk(dir_path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
def send_notification(old_size, new_size):
"""发送目录大小变化通知邮件"""
subject = '目录大小变化通知'
body = f'监控目录 {MONITOR_DIR} 的大小已发生变化:\n'
body += f'旧大小: {old_size} 字节\n'
body += f'新大小: {new_size} 字节'
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = SENDER
msg['To'] = RECIPIENT
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(SMTP_USERNAME, SMTP_PASSWORD)
server.send_message(msg)
def monitor_dir_size():
"""监控目录大小变化"""
old_size = get_dir_size(MONITOR_DIR)
while True:
time.sleep(3600) # 每隔1小时检查一次
new_size = get_dir_size(MONITOR_DIR)
if new_size != old_size:
send_notification(old_size, new_size)
old_size = new_size
if __name__ == '__main__':
monitor_dir_size()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
上次更新: 2024/12/04, 17:15:49