Server Backup using RC Interrupt
This is an archive of my engineering project from 2017 subject Network Programming Lab, performed on Redhat 6.
This system provides automatic backup functionality for server files during system shutdown or reboot.
- Components
- server-backup.sh: Main backup script
- server-backup (init.d): RC script for shutdown/reboot integration
- Features
- Automatic backup prompt during shutdown/reboot
- Timestamped backups
- Compression using tar.gz format
- Color-coded status messages
- Both interactive and forced backup modes
Installation Follow the setup instructions.
Usage
- Manual backup: $ sudo /usr/local/
2. Code
- Main backup script:
#!/bin/bash
# /usr/local/bin/server-backup.sh
# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color
# Backup source and destination
SOURCE_DIR="/var/www" # Change this to your server files location
BACKUP_DIR="/backup" # Change this to your backup location
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_NAME="server_backup_$TIMESTAMP"
backup_files() {
echo -e "${GREEN}Starting backup of server files...${NC}"
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
# Create the backup using tar
tar -czf "$BACKUP_DIR/$BACKUP_NAME.tar.gz" "$SOURCE_DIR" 2>/dev/null
if [ $? -eq 0 ]; then
echo -e "${GREEN}Backup completed successfully!${NC}"
echo "Backup stored in: $BACKUP_DIR/$BACKUP_NAME.tar.gz"
return 0
else
echo -e "${RED}Backup failed!${NC}"
return 1
fi
}
# If script is run directly, ask for confirmation
if [ "$1" != "--force" ]; then
read -p "Do you want to backup server files? (y/n): " answer
case $answer in
[Yy]* ) backup_files;;
* ) echo "Backup cancelled";;
esac
else
backup_files
fi
- RC script that will be called during shutdown/reboot:
#!/bin/bash
# /etc/init.d/server-backup
### BEGIN INIT INFO
# Provides: server-backup
# Required-Start: $local_fs $network
# Required-Stop: $local_fs $network
# Default-Start: 0 6
# Default-Stop:
# Short-Description: Backup server files during shutdown/reboot
# Description: A script to backup server files when system is shutdown or rebooted
### END INIT INFO
case "$1" in
start)
# Nothing to do on start
;;
stop)
/usr/local/bin/server-backup.sh --force
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
;;
esac
exit 0
- Setup instructions:
# 1. Create the backup script
sudo nano /usr/local/bin/server-backup.sh
# (Copy the first script into this file)
# 2. Make it executable
sudo chmod +x /usr/local/bin/server-backup.sh
# 3. Create the RC script
sudo nano /etc/init.d/server-backup
# (Copy the second script into this file)
# 4. Make RC script executable
sudo chmod +x /etc/init.d/server-backup
# 5. Register the script to run during shutdown/reboot
sudo update-rc.d server-backup defaults 0 6
# 6. Create backup directory
sudo mkdir -p /backup
sudo chmod 755 /backup