Skip to content

Instantly share code, notes, and snippets.

@sbchisholm
Last active December 15, 2015 23:19
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 sbchisholm/5338986 to your computer and use it in GitHub Desktop.
Save sbchisholm/5338986 to your computer and use it in GitHub Desktop.
Backs up the files/folders according to the configuration in config.json. Will send an reporting the success or failure of the rsyncs.
#!/usr/bin/python
#
# Backs up the files/folders according to the configuration in config.json. Will
# send an reporting the success or failure of the rsyncs.
import json, os, smtplib, ast, datetime
from email.mime.text import MIMEText
def email_backup_failures(config, failed_backups, failed = True):
# build message body
if not failed:
if config['report_success']:
email_body = 'Backup completed SUCCESSFULLY'
else:
return
else:
email_body = 'The following backups FAILED:'
for failure in failed_backups:
email_body += '\n %s' % failure
# build message object
msg = MIMEText(email_body)
msg['Subject'] = 'Backup script REPORT - %s - [%s]' % (
datetime.datetime.now(),
os.path.realpath(__file__))
msg['From'] = config['email_from']
msg['To'] = ", ".join(config['email_to'])
# send message
smtp_server = smtplib.SMTP(
config['email_smtp_server'],
config['email_smtp_port'])
smtp_server.login(
str(config['email_smtp_username']),
str(config['email_smtp_password']))
smtp_server.sendmail(
config['email_from'],
config['email_to'],
msg.as_string())
smtp_server.quit()
def get_log_filename(config):
if config['log_file_path_relative']:
script_dir = os.path.dirname(os.path.realpath(__file__))
return os.path.join(script_dir, config['log_file'])
else:
return config['log_file']
def print_log_header(config):
log_file = open(get_log_filename(config), 'a')
log_file.write('%s [INFO] #### Begin Backup ####\n' % (
datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')))
log_file.close();
def backup():
config = json.loads(open('config.json', 'r').read())
failed_backups = []
print_log_header(config)
for source in config['backup_sources']:
rsync_command = 'rsync -vur --delete --exclude=%s --log-file=%s %s %s' % (
config['rsync_excludes'],
get_log_filename(config),
source,
config['backup_server_location'])
# keep track of the failed rsync commands
if (os.system(rsync_command)):
failed_backups.append(rsync_command)
# report by email
email_backup_failures(
config,
failed_backups,
failed = len(failed_backups) > 0)
if __name__ == '__main__':
backup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment