Skip to content

Instantly share code, notes, and snippets.

@notesbytom
Created April 4, 2019 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notesbytom/bdc68ef8ce06e3cb4f0b50037d1dba68 to your computer and use it in GitHub Desktop.
Save notesbytom/bdc68ef8ce06e3cb4f0b50037d1dba68 to your computer and use it in GitHub Desktop.
MySQL Backup Example Python Script
#!/usr/bin/python
import datetime
import os.path
import os
# Update these to match your environment, schedule with crontab
dbs = ['db_one','db_two','db_three']
outfolder = '/var/backup/mysql'
numToKeep = 7
mydate = "{:%Y-%m-%d_%H%M}".format(datetime.datetime.now())
for db in dbs:
# Create New Backup
outfile = os.path.join(outfolder,'{}_{}.gz'.format(mydate,db))
cmd = 'mysqldump {} | gzip > {}'.format(db,outfile)
print('cmd = {}'.format(cmd))
os.system(cmd)
# Cleaup Old Backups
l = [f for f in sorted(os.listdir(outfolder)) if f.endswith('{}.gz'.format(db))]
print('Num DB Backups for {} = {}'.format(db, len(l)))
removeList = l[:-numToKeep]
keepList = l[-numToKeep:]
for f in removeList:
cmd = 'rm {}'.format(os.path.join(outfolder,f))
print(cmd)
os.system(cmd)
for f in keepList:
print('KEEP {}'.format(f))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment