Date created: 03/16/11 19:45:06. Last modified: 03/26/17 11:18:12

Backup VirtualBox Machines

A script wich grabs the name of the first .vdi file for the VM specified, makes a copy of it in a local folder and then rsync's the local .vdi archive to a remote server.

# script to stop the VM specified, copy its first .vdi hard drive file and then start the VM again
# arguments: ./this_script_name VM_Name Local_VM_Archive_Path Receiver_Email_Address remoteuser@remotehost:/remote/backup/path

# Grab the .vdi location of the first drive, drive 0,0
vdiPath=$(VBoxManage showvminfo $1 | grep "`VBoxManage showvminfo $1 | grep "Storage Controller Name (0)" | awk '{print $5}'` Controller (0, 0)" | awk '{print $5}')
# Build the backup path
backupPath=$2/`date +%Y-%m-%d--%H-%M-%S`-`basename $vdiPath` # 2010-25-12--17-30-00-my_drive.vdi
emailAddress=$3 # reports@mydomain.tld
rsyncDest=$4 # backupuser@backupfileserver:/backups/VMs

# Prep the email assuming success
MailSubject="VM Backup Succeeded"
echo "VM guest $VM was successfully copied from $vdiPath to $backupPath" > $MailMessage

# Shutdown the virtual machine and give it time to make sure it has shut down
VBoxManage controlvm $VM acpipowerbutton &
sleep 30

# Make sure we don't have too many archives of the VM taking up all our space!
find /pfSense-Archive -maxdepth 1 -type f -mtime +6 | xargs rm

# Copy the VM vdi
result=`cp $vdiPath $backupPath 2>&1`
# If the copy failed (didn't exit with a status of 0)
if [ $? -ne 0 ]; then
        echo "There was a problem with the copy"

        # Adjust the email to be sent
        MailSubject="VM Backup Failed"
        echo "VM guest $VM was not backed up from $vdiPath to $backupPath" > $MailMessage
        echo "$result" >> $MailMessage

# Start the VM
VBoxHeadless -s $VM -v off &

# Sync the local VM archive with the backup destination
result=`rsync -vhrP $2 $rsyncDest 2>&1`
# If rsync failed
if [ $? -ne 0 ]; then
        echo "There was a problem with rsync"

        # Adjust the email to be sent
        MailSubject="VM Backup Failed"
        echo "The local VM archive was not sync'd to $rsyncDest" >> $MailMessage
        echo "$result" >> $MailMessage

ssh vmbackup@vmhost "find /pfSense-Archive -maxdepth 1 -type f -mtime +29 | xargs rm"

df -hT > $space
echo "Remaining drive space:" >> $MailMessage
cat $space >> $MailMessage
rm $space

# Email the result
cat $MailMessage | mail -s "$MailSubject" "$MailTo"

rm $MailMessage

Previous page: IOS-XRv Example