Automating rsync Backups with Cron and Process Checking
Too automate data backups to another directory, it's crucial to verify if rsync is already runing before initiating a new backup. This prevents multiple rsync processes from overloading the server, which can cause performance issues or crashes.
Setting Up SSH Key Authentication to Passwrodless rsync
-
Generate an SSH key pair on the source server:
ssh-keygenPress Enter to accept default settings.
-
Copy the public key to the remote backup server:
ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.1.100Enter the remote server password when prompted.
Configuring Cron for Scheduled Backups
Add a cron job to run the backup script every 5 minutes:
crontab -l
*/5 * * * * bash /usr/local/mail/backrsync.sh
Backup Script with Process Checking
Create a script that checks for eixsting rsync processes before executing backups:
#!/bin/bash
# Script: backup_script.sh
LOG_FILE="/var/log/backup_log"
CURRENT_TIME=$(date "+%Y-%m-%d %H:%M:%S")
log_message() {
local print_to_console=$1
local message="$CURRENT_TIME $2"
if [ $print_to_console -eq 1 ]; then
echo "$message"
fi
echo "$message" >> "$LOG_FILE"
}
validate_command() {
local exit_code=$?
if [ $exit_code -ne 0 ]; then
log_message 1 "#[ERROR] Command failed: $1"
exit 1
fi
}
log_message 1 "Backup process initiated"
# Check for existing rsync processes
ps -ef | grep 'rsync' | grep -v 'grep' | grep -v 'backup_script'
if [ $? -ne 0 ]; then
log_message 1 "Starting backup..."
log_message 0 "Cron job triggered at $CURRENT_TIME"
backup_target="/umaildataback/backup"
if [ -d "$backup_target" ]; then
/usr/bin/rsync -rav /home/mailbox "$backup_target/"
validate_command "rsync /home/mailbox"
/usr/bin/rsync -rav /usr/local/mail/data/mailbox /mailbackmailbox/
validate_command "rsync /usr/local/mail/data/mailbox"
/usr/bin/rsync -rav /usr/local/mail/data/backup/ /mailbackmailbox/mysqlback/
validate_command "rsync /usr/local/mail/data/backup"
log_message 0 "Backup completed successfully"
else
log_message 1 "Backup directory $backup_target not found"
fi
else
log_message 1 "rsync already running, skipping this cycle"
log_message 0 "$CURRENT_TIME: Process already active"
fi
log_message 1 "Backup process completed"
Restarting the Cron Service
After setting up the script, restart the cron service to apply changes:
/etc/init.d/crond restart