Prepared by: Anwer Sadath Abdhul Muttaliff
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
.
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"
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
Grant execution permissions to the script:
chmod +x backup.sh
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
Generate SSH keys and copy the public key to the remote server for password-less authentication:
ssh-keygen
ssh-copy-id anwer@192.168.1.87
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
Run the script manually to verify its functionality:
./backup.sh
Check the backup directories and log file to ensure the backup was successful.
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
Compare the time taken for manual and automated backups to calculate efficiency gain: