Skip to content

Instantly share code, notes, and snippets.

@ColeMundus
Last active September 18, 2020 23:26
Show Gist options
  • Save ColeMundus/c27ea5c1abbdf6ced4ba7cc17980c594 to your computer and use it in GitHub Desktop.
Save ColeMundus/c27ea5c1abbdf6ced4ba7cc17980c594 to your computer and use it in GitHub Desktop.
import subprocess, argparse, time, os, math
from datetime import date, datetime
from mcrcon import MCRcon
parser = argparse.ArgumentParser()
parser.add_argument('--target', help='Path to target backup directory', required=True)
parser.add_argument('--server', help='Server IP address', required=True)
parser.add_argument('--port', help='Server port', default=25575, required=False)
parser.add_argument('--password', help='Server rcon password', required=True)
parser.add_argument('--output', help='Path to backups output directory', required=True)
parser.add_argument('--command_logging', help='Flag to control command logging', default=True)
args = parser.parse_args()
command_logging = args.command_logging
if args.output[-1] == '/':
output_directory = args.output
else:
output_directory = args.output + '/'
# helper functions
def log(*args):
if command_logging:
print('\u001b[32m'+ args[0], *args[1:])
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
log('# Starting minecraft server backup script')
log('# Target backup directory:', args.target)
log('# Connecting to running server')
log('# Starting rcon client')
with MCRcon(args.server, args.password, port=args.port) as mcr:
log('# Connected')
log('# Sending save command')
response = mcr.command('say Starting Server Backup')
response = mcr.command('save-all')
response = mcr.command('save-off')
log('# Sleeping to allow save to complete')
time.sleep(4)
log('# Save complete')
log('# Starting directory backup')
now = datetime.now()
filename = now.strftime("%Y-%m-%d_%H.%M_") + args.server + '_' + args.target.split("/")[-2] + '_server_backup.tar.gz'
log('# Archiving to', filename)
start_time = time.time()
subprocess.run(['tar', '-cvzf', output_directory + filename, args.target])
time_elapsed = time.strftime('%M:%S', time.gmtime(time.time()-start_time))
backup_size = convert_size(os.stat(output_directory + filename).st_size)
log('# Backup size:', backup_size)
log('# Backup completed in ' + time_elapsed + ', re-enabling autosave')
response = mcr.command('save-on')
response = mcr.command('say Server Backup Complete, §oTime Elapsed: ' + time_elapsed + ", §oBackup §oSize: §o" + backup_size)
log('# Done', '\u001b[0m')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment