Super Nerdy Cool

My (technical) adventures through the professional world…
June 24, 2009

Backup my google calendars via shell and python scripts and scheduling them via cron

So recently my calendar got messed up a little (dupes) due my mobile phone (HTC Touch Pro running Windows Mobile 6.1) resetting [syncing again messed it up]. I realize (now???) I need to keep backups of my calendars and contacts.

I took the following script online (which requires python and the gdata module):

#! /usr/bin/python

## This script backs up my google contacts
## http://www.joet3ch.com/2008/09/25/backup-google-contacts/

import gdata.contacts.service
gd_client = gdata.contacts.service.ContactsService()
gd_client.ClientLogin('uname@domain.com', 'password')
query = gdata.contacts.service.ContactsQuery()
query.max_results = 2000 # change for max contacts returned
feed = gd_client.GetContactsFeed(query.ToUri())
print feed

and adapted the following script to backup my calendars and contacts:

#! /bin/bash

## This script backs up my calendars -- will use with Cron to backup daily.
## following is adapted from http://permanentinkdesign.com/articles/backing-up-a-google-calendar/
INCREMENT=`date +%Y%m%d%H%M`
DIR="$HOME/Documents/Backup_Google"
USERNAME="uname@domain.com"
PASSWORD="mypassword"
## Vinh's calendar
curl -s url-to-private-ics -o "$DIR/Vinh_$INCREMENT.ics"
## TNTTSP's calendar'
curl -s url-to-private-ics -o "$DIR/TNTTSP_$INCREMENT.ics"
## Birthdays
curl -s url-to-private-ics -o "$DIR/Birthdays_$INCREMENT.ics"

## Now backup Google Contacts
## http://www.joet3ch.com/2008/09/25/backup-google-contacts/
$HOME/Documents/bin/Backup_Google_Contacts.py > ${DIR}/VinhContacts_$INCREMENT.xml

## Now backup Google Reader subscriptions
## http://www.clausconrad.com/blog/backup-google-reader-subscription-list-to-opml-automatically
$HOME/Documents/bin/gr-opml-backup.py $USERNAME $PASSWORD > Vinh_GoogleReaderSubs_$INCREMENT.opml

find $DIR -mtime +14 -exec rm -f {} \;

Every time the script runs, it backs up my 3 calendars and contacts. The very last line says delete if files are 14 days or older.

Now, to set up my crontab to run this everyday at 10pm, I type “crontab -e” in the shell. I put

00 22 * * * $HOME/Documents/bin/Backup_Google.sh

when vi (or your default visual editor) opens up.

More info about cron on the Mac is here.

Sometimes, you might not want to schedule a recurring script. To run a script once, we can rely on the at (“at”) command. More information here and here. However, the at command didn’t work on my Macbook when I tried it a while back.

UPDATE: The script above (Backup_Google.sh) is updated to include the google reader subscription, thanks to this site.

Leave a Comment