You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.7 KiB

1 year ago
from Util.OssUtil import *
from Util.CommonUtil import *
# 备份思路:
# 使用Navicat备份然后上传到OSS
# 参考文档https://blog.csdn.net/weixin_56631459/article/details/133904669
# 备份的目录:
# C:\Users\Administrator\Documents\Navicat\PostgreSQL\Servers\10.10.14.71\huiya_db\public
# 遍历目录下所有nb3文件删除30天前的文件
import os
from datetime import datetime
# PostgreSQL 配置
backup_dir = r'C:\Users\Administrator\Documents\Navicat\PostgreSQL\Servers\10.10.14.71\huiya_db\public'
def calculate_days_difference(timestamp_str):
# 将文件名中的时间戳字符串转换为datetime对象
file_datetime = datetime.strptime(timestamp_str, "%Y%m%d%H%M%S")
# 获取当前的datetime
current_datetime = datetime.now()
# 计算两个datetime之间的差异并转换为天数
time_difference = current_datetime - file_datetime
days_difference = time_difference.days
return days_difference
if __name__ == '__main__':
auth = oss2.Auth(accessKeyId, accessKeySecret)
bucket = oss2.Bucket(auth, endpoint, bucketName)
paths = os.walk(backup_dir)
for path, dir_lst, file_lst in paths:
for file_name in file_lst:
if file_name.endswith(".nb3"):
timestamp_str = file_name.replace(".nb3", "")
days_diff = calculate_days_difference(timestamp_str)
# print(f"时间戳与当前时间相差 {days_diff} 天")
if days_diff > 30:
os.remove(os.path.join(path, file_name))
printf("发现30天前的备份文件已删除掉" + file_name)
else:
# 上传所有nb3文件到oss上去如果上面已经存在则跳过
prefix = 'DataBaseBackup/'
key = prefix + file_name
if not bucket.object_exists(key):
uploadOss(key, os.path.join(path, file_name))
printf(f"上传文件 {file_name} 到oss成功。")
else:
# 获取文件元信息
meta = bucket.head_object(key)
if meta.content_length != os.path.getsize(os.path.join(path, file_name)):
bucket.delete_object(key)
uploadOss(key, os.path.join(path, file_name))
printf(f"文件已存在,但文件大小不一致,已删除并重新上传 {file_name} 到oss成功。")
else:
printf(f"文件 {file_name} 已经存在oss上。")
printf("恭喜,所有备份操作成功完成!")