MC服务器备份脚本

发布时间:2024年01月15日

前言

最近开了个mc服务器,为了提高数据的安全性,使用python写了个简单的备份脚本

备份存档数据

代码如下:

# -*- coding: utf-8 -*-

import os
import zipfile
import datetime

# 设置备份目录和备份文件名
backup_dir = "/home/minecraft/backups"
server_path = "/data/server"

def backup_minecraft_server():
    # 切换到服务器目录
    os.chdir(server_path)

    # 备份world世界
    world_backup_file = "world_{}.zip".format(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
    with zipfile.ZipFile(os.path.join(backup_dir, world_backup_file), "w", zipfile.ZIP_DEFLATED) as archive:
        for root, dirs, files in os.walk("world"):
            for file in files:
                archive.write(os.path.join(root, file))

    # 备份world_nether世界
    nether_backup_file = "world_nether_{}.zip".format(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
    with zipfile.ZipFile(os.path.join(backup_dir, nether_backup_file), "w", zipfile.ZIP_DEFLATED) as archive:
        for root, dirs, files in os.walk("world_nether"):
            for file in files:
                archive.write(os.path.join(root, file))

    # 备份world_the_end世界
    end_backup_file = "world_the_end_{}.zip".format(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
    with zipfile.ZipFile(os.path.join(backup_dir, end_backup_file), "w", zipfile.ZIP_DEFLATED) as archive:
        for root, dirs, files in os.walk("world_the_end"):
            for file in files:
                archive.write(os.path.join(root, file))

    # 合并备份文件
    merged_backup_file = "minecraft_backup_{}.zip".format(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
    with zipfile.ZipFile(os.path.join(backup_dir, merged_backup_file), "w", zipfile.ZIP_DEFLATED) as archive:
        archive.write(os.path.join(backup_dir, world_backup_file), arcname="world.zip")
        archive.write(os.path.join(backup_dir, nether_backup_file), arcname="world_nether.zip")
        archive.write(os.path.join(backup_dir, end_backup_file), arcname="world_the_end.zip")

    # 删除临时备份文件
    os.remove(os.path.join(backup_dir, world_backup_file))
    os.remove(os.path.join(backup_dir, nether_backup_file))
    os.remove(os.path.join(backup_dir, end_backup_file))

    # 删除7天前的备份
    for file_name in os.listdir(backup_dir):
        file_path = os.path.join(backup_dir, file_name)
        if os.path.isfile(file_path):
            file_time = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
            if (datetime.datetime.now() - file_time).days > 7:
                os.remove(file_path)

if __name__ == "__main__":
    backup_minecraft_server()

添加定时任务

0 3 * * * python /path/to/backup.py

每天凌晨三点备份?

后续添加

1.异地备份(OSS对象存储)

2.查看备份日志

文章来源:https://blog.csdn.net/cjj2006/article/details/135608679
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。