off-site backup to Amazon EBS using dirvish
Language: Python
#!/usr/bin/env python -t
# encoding: utf-8
# origin: http://overt.org/2010/02/15/off-site-backup-for-010gb-using-dirvish-and-amazon-ec2-and-ebs/
"""
run_offsite_backups.py
Wake up the EC2 backup server, run dirvish backup, then shut it down
Created by Bryan Klingner (code.b@overt.org) on 2010-02-02.
Feel free to use this code yourself. Maybe email me if you do :)
"""
import sys
import os
import boto
import time
import subprocess
BACKUP_INSTANCE_ID = 'YOUR_INSTANCE_ID'
def main():
conn = boto.connect_ec2()
# get the backup instance object
instance = conn.get_all_instances(instance_ids=(BACKUP_INSTANCE_ID,))[0].instances[0]
# if the instance is stopped, start it up
if instance.state != 'running':
conn.start_instances(instance_ids=(BACKUP_INSTANCE_ID,))
waited = 0
while instance.state != 'running':
instance.update()
sys.stdout.write("\rInstance starting up (%d sec)..." % (waited))
sys.stdout.flush()
time.sleep(1)
waited += 1
print "\n"
print "Backup instance running:"
print " ID: ", instance.id
print " State: ", instance.state
print " DNS name: ", instance.dns_name
# chill for a few seconds so the SSH server is listening
time.sleep(10)
print ""
print "Initiating backup..."
retcode = ssh_cmd('dirvish-expire; dirvish-runall', instance.dns_name, user='username')
print ""
# backup is done; shut down the instance
conn.stop_instances(instance_ids=(BACKUP_INSTANCE_ID,))
waited = 0
while instance.state != 'stopped':
instance.update()
sys.stdout.write("\rInstance shutting down (%d sec)..." % (waited))
sys.stdout.flush()
time.sleep(1)
waited += 1
print ""
def ssh_cmd(cmd, host, user='root'):
""" Run a shell command on a remote server via ssh """
ssh_cmd = 'ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no ' + user + '@' + host + " '%s'" % (cmd)
print "Running SSH command: %s" % ssh_cmd
returncode = subprocess.call(ssh_cmd, shell=True)
#logging.debug( output, returncode )
return returncode
if __name__ == '__main__':
main()
Reveal More

