import os, time, sys, zipfile, datetime,calendar from os import sep # Script Parameters # Target Directory for final Zip files target_dir = r'target' # The name of the sql file (this will be the same for all backups) file_name = 'databases.sql' # Authentication user = 'username' password = 'password' # The command for the mysql dump. This could include the entire path to the executable if mysqldump is not on the path environment variable dumpcmd = r'mysqldump' # The host you want to connect to host = 'example.com' args = [dumpcmd, '-C', '-f', '--host=%s' %host, '--user=%s' %user, '--password=%s' %password, '--result-file=%s' %file_name, '--all-databases'] os.chdir(target_dir) cmd = ' '.join(args) print 'Running Command: %s' %cmd.replace(password, '*'*len(password)) os.system(cmd) # Below is for zipping the files and creating a redundant backup def getZipFileName(): # Set time variables ( # Note: you don't have to use some of them, # but they make the script easier to understand t = time.time(); g = time.gmtime(t) year = g[0]; month = g[1]; day = g[2] try: datetime.date(year, month, day+1) except: # Last day of the month, return month name root = time.strftime('%Y', g) if not os.access(root, os.F_OK): os.mkdir(root) return os.path.join(root, '%s.zip' %time.strftime('%b')) if int(time.strftime('%w', g)) == 0: # Last day of week, return week number cal_month = calendar.monthcalendar(year, month) for week in cal_month: if day in week: return 'Week%i.zip' %month.index(week) # Just a regular weekday... return '%s.zip' %time.strftime('%A') # Write the zip file zip_name = getZipFileName() zip_file = os.path.abspath(zip_name) zip = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) zip.write(file_name) zip.close() # Remove uncompressed sql file os.remove(file_name) to_path = os.path.join(copy_dir, zip_name) to_dir = sep.join(to_path.split(sep)[:-1]) if not os.access(to_dir, os.F_OK): os.makedirs(to_dir) if os.access(to_path, os.F_OK): os.remove(to_path) shutil.copy(zip_file, to_path)