Skip to content

Instantly share code, notes, and snippets.

@arthurfurlan
Created April 29, 2011 20:44
Show Gist options
  • Select an option

  • Save arthurfurlan/949010 to your computer and use it in GitHub Desktop.

Select an option

Save arthurfurlan/949010 to your computer and use it in GitHub Desktop.
Encrypted backup
#!/bin/bash
# written by Arthur Furlan <afurlan@valvim.com>
# check program usage
if [ $# -lt 1 ]; then
echo "Usage: $0 DEVICE"
exit 1
elif ! [ -e "$1" ]; then
echo "Error: device '$1' not found."
exit 2
elif ! [ -b "$1" ]; then
echo "Error: device '$1' is not a block device."
exit 3
fi
CRYPT_KEY='/path/secret.key'
CRYPT_LBL='device-label'
MOUNT_DIR='/mnt/mount-dir'
REMOT_SSH='your-backup-user@example.com'
REMOT_DIR='/remote/dir/'
LOCAL_DIR="$MOUNT_DIR/local/dir/"
LOCAL_KEY="/path/to/ssh/key"
is_device_created() {
dmsetup ls | grep $CRYPT_LBL > /dev/null
return $?
}
function is_device_mounted {
mount | grep "$MOUNT_DIR" > /dev/null
return $?
}
is_device_created
if [ "$?" = "1" ]; then
echo -n "Creating encrypted device \"$1\"... "
cryptsetup create $CRYPT_LBL $1 --key-file $CRYPT_KEY && echo 'OK'
else
echo 'Encrypted device already created... OK'
fi
is_device_mounted
if [ "$?" = "1" ]; then
echo -n "Mounting device on directory \"$MOUNT_DIR\"... "
mount $MOUNT_DIR && echo 'OK'
else
echo 'Device directory already mounted... OK'
fi
echo
echo 'Syncing with remote server... '
rsync -aH -e "ssh -i $LOCAL_KEY" $REMOT_SSH:$REMOT_DIR $LOCAL_DIR && echo 'OK'
echo
is_device_mounted
if ! [ "$?" = "1" ]; then
echo -n "Umounting device on \"$MOUNT_DIR\"... "
umount $MOUNT_DIR && echo 'OK'
else
echo 'Device directory already unmounted... OK'
fi
is_device_created
if ! [ "$?" = "1" ]; then
echo -n "Removing encrypted device \"$1\"... "
cryptsetup remove $CRYPT_LBL 2> /dev/null && echo 'OK'
else
echo 'Encrypted device already removed... OK'
fi
echo -n "Checking if device \"$1\" still is mounted... "
is_device_mounted || echo 'OK'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment