Bill Lovett

Gmail, GPG, and Backups via Email

I have a Gmail account, but hardly any reason to use it. My personal email needs are already being met just fine and I really have no business having a Gmail account at all. But I do, and ever since I got it I've been trying to think up something useful to do with it. I've decided to turn that 1 gigabyte of space into an off-site repository for backup files. Here's how I'm doing it:

 #!/bin/bash
 
 DATE=`date +%F-%R`;
 BZFILE=/tmp/$DATE.sql.bz2;
 GPGFILE=$BZFILE.gpg;
 mysqldump --all-databases | bzip2 -c --best > $BZFILE;
 gpg --encrypt -r me@example.com $BZFILE;
 echo 'MySQL backup from abominus is attached' |  mutt -a $GPGFILE \ 
 -s '[backup] MySQL backup' self@gmail.com
 rm $GPGFILE;
 

This bash script is specific to MySQL backups, but the overall idea could be applied to other types of backup tasks too. After setting up a few variables, the script dumps all my MySQL databases via mysqldump and pipes them into bzip for compression. Then it uses gpg to encrypt (presumably, you've already run gpg --gen-keys) the resulting bz2 file such that my key is the only one that will be able to decrypt it. Finally, the script calls upon mutt to send the gpg-encrypted file as an attachment to my Gmail address. Run the script from a cron job every morning, and you've got yourself a simple and specific backup system.

I went with bzip over gzip because I wanted maximum compression. Gmail caps message sizes-- both incoming and outgoing-- at 10M, so smaller is better. That cap also means certain doom if you're trying to back up something especially big. If my bzip file ended up being larger than 10M, I'd need a way of slicing it into segments and sending multiple messages with one segment each. Sounds complicated, and probably not worth the effort.

The ability to encrypt the file is the lynch pin of the whole operation. Even though my data isn't especially sensitive, it doesn't seem like a good idea to just toss it into a foreign mail system and assume that everything will be fine.

Aside from MySQL backups, a script like this could be a nice way to create offsite backups of a wiki or even the files of your website. Bzip compression is pretty impressive-- the file I get from MySQL dump is 29M, but bzip squeezes that down to a scrawny 3.2M.

On the downside, there's no automatic way to delete old backups from Gmail. They'll just accumulate until you delete them manually. Whether or not that's inconvenient probably depends on your particular circumstances. Since the script lets you format the message subject however you like, it should be easy enough to create filters in Gmail that will tag them accordingly.