脚本功能:
1、自动备份mysql全库,自动删除一周前备份,数据有效期为一周。
2、自动备份网站数据,自动删除三个月前备份,数据有效期三个月;每月1号执行目录完全备份,其余时间增量备份。
3、对备份数据进行权限控制,防止恶意人员查看修改,若以root权限执行脚本,则其他用户对备份数据没有任何权限。
#!/bin/bash
#
#lampp mysql databases and web data backup bash;
#mysql backup data keep 7 days;
#website backup data keep 3 months and incremental backup in per month.
#author:LinuxPad
#website:www.linuxpad.cn
#mail:linuxpad.cn(at)gmail.com
#created:26 November 2012
#Mysql dabase information
db_host="localhost"
db_user="root"
db_passwd=""
MYSQL="/opt/lampp/bin/mysql"
MYSQLDUMP="/opt/lampp/bin/mysqldump"
#Path information
WEBHOME="/opt/lampp/htdocs/blog"
BACKUP_DB="/opt/backup/database"
BACKUP_WEB="/opt/backup/web"
#Time information
time=`date +"%Y-%m-%d"`
day=`date +"%d"`
month=`date +"%Y-%m"`
weekday=`date +"%u"`
#Path enable write
if [ ! -w "$BACKUP_DB" ] && [ ! -w "$BACKUP_WEB"]; then
chmod -R 700 $BACKUP_DB $BACKUP_WEB
fi
#Mysql Backup
$MYSQLDUMP -u $db_user -p$db_passwd -h $db_host --all-databases > $BACKUP_DB/$time
cd $BACKUP_DB && tar -czf $time.tar.gz $time && rm -rf $time && chmod go-rwx $time.tar.gz
if [ $weekday == "1" ]; then
find $BACKUP_DB -mtime +7 | xargs rm -rf {}
fi
#Website Backup
if [ ! -d $BACKUP_WEB/$month ];then
mkdir $BACKUP_WEB/$month
touch $BACKUP_WEB/$month/$month
chmod -R go-rwx $BACKUP_WEB/$month
fi
cd $BACKUP_WEB/$month && tar -g $month -czf $time.tar.gz $WEBHOME && chmod go-rwx $time.tar.gz
if [ $day == "01" ]; then
find $BACKUP_WEB -mtime +90 | xargs rm -rf{}
fi
使用脚本前需在/opt下事先建立好目录
mkdir -p /opt/backup/{database,web} chmod -R go-wrx /opt/backup
添加计划任务
假设脚本位置为/root/cron/backup.sh,每天2点执行备份
crontab -e 添加以下内容 0 2 * * * /root/crontab/backup.sh 2>/root/crontab/backup.log