Backup Automation Project

Prepared by: Anwer Sadath Abdhul Muttaliff

Project Overview

This project automates the backup process in a home lab environment using rsync. It ensures data integrity and security by synchronizing data from a local host to a backup directory and a remote server. The script is executed daily using cron.

Project Steps

1. Define Source and Backup Directories

Define the directories to be backed up and the destination directories on both local and remote systems:

SOURCE_DIR="/home/*"
BACKUP_DIR="/backup/home_backup"
LOG_FILE="/var/log/backup.log"
REMOTE_SERVER="anwer@192.168.1.87"
REMOTE_BACKUP_DIR="/home/anwer/backup_localhost_home"
2. Create the Backup Script

Create a script (backup.sh) to automate the backup process:

#!/bin/bash

# Define source and backup directories
SOURCE_DIR="/home/*"
BACKUP_DIR="/backup/home_backup"
LOG_FILE="/var/log/backup.log"

# Create backup directory if it doesn't exist
sudo mkdir -p $BACKUP_DIR

# Log the start time
echo "Backup started at $(date)" >> $LOG_FILE

# Perform the backup using rsync
sudo rsync -arv --delete $SOURCE_DIR $BACKUP_DIR >> $LOG_FILE 2>&1

# Redundant backup using rsync to remote server
sudo rsync -arv --delete -e "ssh -i /home/anwer/.ssh/id_rsa" $SOURCE_DIR $REMOTE_SERVER:$REMOTE_BACKUP_DIR >> $LOG_FILE 2>&1

# Log the end time and calculate duration
END_TIME=$(date +%s)
START_TIME=$(date -d "$(head -n 1 $LOG_FILE | awk '{print $4, $5}')" +%s)
DURATION=$((END_TIME - START_TIME))

echo "Backup completed at $(date)" >> $LOG_FILE
echo "Backup duration: $DURATION seconds" >> $LOG_FILE
3. Make the Script Executable

Grant execution permissions to the script:

chmod +x backup.sh
Make Script Executable
4. Configure sudo Privileges

Allow the anwer user to run specific commands with sudo without requiring a password:

sudo visudo

Add the following line to the sudoers file:

anwer ALL=(ALL) NOPASSWD: /usr/bin/rsync, /bin/mkdir
5. Set Up SSH Key-Based Authentication

Generate SSH keys and copy the public key to the remote server for password-less authentication:

ssh-keygen
SSH Key Generation
ssh-copy-id anwer@192.168.1.87
SSH Key Copy
6. Configure Permissions

Ensure the anwer user has the necessary permissions for the backup directory and log file:

sudo chown -R anwer:backup /backup
sudo chmod 775 /backup
sudo chown root:backup /var/log/backup.log
sudo chmod 664 /var/log/backup.log
7. Test the Script

Run the script manually to verify its functionality:

./backup.sh

Check the backup directories and log file to ensure the backup was successful.

Local Backup Directory Remote Backup Directory
8. Schedule the Script with Cron

Automate the script to run daily using cron:

crontab -e

Add the following line to schedule the script to run at 2 AM daily:

0 2 * * * /path/to/backup.sh
9. Measure Time Saved

Compare the time taken for manual and automated backups to calculate efficiency gain:

Best Practices

Back to Top Back to Home