备份文件并发送邮件通知
内容如下
import os
import tarfile
import datetime
import smtplib
from email.mime.text import MIMEText
# 设置要备份的目录路径
SOURCE_DIR = '/root/deploy'
# 设置备份文件保存路径
BACKUP_DIR = '/data/backup'
# 设置发送邮件的参数
SENDER = 'xxx@qq.com'
RECIPIENT = 'xxxx@163.com'
SMTP_SERVER = 'smtp.qq.com'
SMTP_PORT = 587
SMTP_USERNAME = 'xxx@qq.com'
SMTP_PASSWORD = 'xxx'
def create_archive(source, dest):
"""创建tar.gz归档文件"""
archive_name = os.path.basename(source) + '_' + datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.tar.gz'
archive_path = os.path.join(dest, archive_name)
with tarfile.open(archive_path, 'w:gz') as tar:
tar.add(source)
return archive_path
def send_notification(archive_path):
"""发送备份完成通知邮件"""
subject = '服务器备份完成通知'
body = f'服务器备份已完成,备份文件位于: {archive_path}'
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)
if __name__ == '__main__':
archive_path = create_archive(SOURCE_DIR, BACKUP_DIR)
send_notification(archive_path)
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
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
上次更新: 2024/12/04, 17:15:49