Skip to content

Instantly share code, notes, and snippets.

@NanoDano
Created July 14, 2020 01:24
Show Gist options
  • Save NanoDano/08368b4469af7bbbda5c22bdd8a2a0b4 to your computer and use it in GitHub Desktop.
Save NanoDano/08368b4469af7bbbda5c22bdd8a2a0b4 to your computer and use it in GitHub Desktop.
Backup, zip, FTP upload, rotate script for Minecraft server
#!/usr/bin/python3
from ftplib import FTP
import glob
from os import system, path, remove
from os.path import join
from datetime import datetime
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
def perform_backup():
current_time = datetime.now().strftime('%Y-%m-%dT%H-%M-%S')
backup_name = f'server-{current_time}'
temp_backup_dir = f'/opt/minecraft/server_backups/server-{current_time}'
system(f'mkdir -p /opt/minecraft/server_backups')
target_zip_file = f'/opt/minecraft/server_backups/server-{current_time}.tar.gz'
logging.info(f'Starting Minecraft backup process {current_time}.')
# Copy dir to operate on
logging.info('Copying server files')
system(f'cp -r /opt/minecraft/server {temp_backup_dir}')
# Archive/compress
logging.info('Archiving and compressing.')
system(f'tar czf {target_zip_file} {temp_backup_dir}')
# Delete temp dir
logging.info('Cleaning up')
system(f'rm -rf {temp_backup_dir}')
logging.info('Backup completed.')
return backup_name + '.tar.gz'
def rotate_backups():
"""Delete old backups so it doesn't fill disk space"""
MAX_BACKUPS = 30
files = glob.glob("/opt/minecraft/server_backups/*.tar.gz")
# Oldest files are at the front. Newest files at the end
files.sort(key=path.getmtime)
logging.info(f'Found {len(files)} files: {files}')
#print(f'Oldest 2 files: {files[:2]}')
#print(f'Newest 2 files: {files[-2:]}')
backup_overflow_count = len(files) - MAX_BACKUPS
logging.info(f'Found {backup_overflow_count} too many backups')
if backup_overflow_count > 0:
for f in files[0:backup_overflow_count]:
logging.info(f'Will remove: {f}')
remove(f)
def upload_over_ftp(file_to_upload):
logging.info(f'Uploading {file_to_upload} over FTP')
with FTP('host', 'user', 'pass') as ftp:
with open(join('/opt/minecraft/server_backups/', file_to_upload), 'rb') as f:
ftp.storbinary(f'STOR minecraft-backups/{file_to_upload}', f)
logging.info('Done uploading over FTP')
def main():
new_backup_file = perform_backup()
rotate_backups()
upload_over_ftp(new_backup_file)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment