Monday, May 28, 2018

Backup and Restore Your Linux System and Home Directory

It's a good idea to regularly back up the files on your computer in case there is ever a hard drive failure.  OSX and Windows comes with basic backup software that is very easy to use.  Simply connect and external USB drive to your computer and enable the backup software.  Google even offers the ability to back up to your Google drive so your data is stored at a different physical location.

Linux system can be backed up very simply through the use of a command line tool called rsync and with a little scripting the backup process can be automated just like it is on OSX and Windows.

Encrypting the Backup Drive

Before backing up your files, it is a good idea to encrypt the external drive where you'll be storing your backups.  This is to prevent someone from taking the external drive and accessing your files.  Use the Disks utilities and select the drive and change it to encrypt the partition.  Note that this means that in the future only a Linux system (along with the password) can access the external drive.

Backing Up the Home Directory

I create two separate backups:  system and home.  The system is to backup my system configuration while the home directory contains the users data.  There are a lot of files and directories in the home directory that doesn't need to be backed up that might be consuming a lot of disk space.  These include cached files, trash files, etc.  It's best to exclude these files and directories. 

I found this file as a good starting point for things to exclude from the home directory.  With this files (modified to your liking), use rsync to back up the home directory (this example is to back up just your own home directory):

rsync -aP --exclude-from=[exclusion file] /home/$USER [path to backup location]
Make sure that you've mounted the external drive and have the path correct.  Use the 'n' option (e.g. rsync -naP ...) to do a dryrun where it it doesn't actually copy any files so you can test first.

If it all works correctly, a crontab to automatically repeat the process can be made although you still need to mount the drive with the encryption passphrase unless you set it up where the cron job has access to the passphrase.  I just create a bash script that I run manually.

Backing Up the System

Backing up the system is very similar except there are some additional directories to exclude and the starting point is "/" instead of the home directory.  

1.  Create a file similar to the one for excluding home directories (see above).  This file is more simple since it only contains directories:
/dev
/proc
/sys
/tmp
/run
/mnt
/media
/lost+found
/home
Then you'd run (again, use -n first to do a dry run):

sudo rsync -aAXv / --exclude-from=[file of excluded directories] [path to backup location]
Note that this time it uses the "sudo" command since some systems files requires SUDO privileges. 

No comments:

Post a Comment