1 前言
笔者针对普通文件准备一个七天循环的备份,计划周一至周六每天循环备份,然后每个周日的数据作为周备上磁带。
2 最佳实践
2.1 创建备份的存储
2.1.1 存储方法介绍
– 此案例使用廉价的NFS和Samba作为后端的存储
– 存储统一使用autofs自动挂载(基于稳定性考量)
– 方案将准备日备份目录“/databackup/dailyBackup”
– 方案将准备周备份目录“/databackup/weeklyBackup”
2.1.2 NFS自动挂载的配置
如果你尚未配置,请参阅以下链接配置,
https://www.cmdschool.org/archives/8449
2.1.3 Samba自动挂载的配置
如果你尚未配置,请参阅以下链接配置,
https://www.cmdschool.org/archives/8434
2.2 创建备份的计划任务
2.2.1 创建备份脚本存放目录
mkdir ~/scripts/
2.2.2 创建备份脚本
vim ~/scripts/databackup.sh
加入如下内容
#!/bin/bash bakDIR=/data dailyBakDIR='/databackup/dailyBackup' weeklyBakDIR='/databackup/weeklyBackup' excludeDIR='/data/lost+found' logFile='/var/log/backup.log' dailyBakKeeptime='+7' weeklyBakKeeptime='+30' Today="`date +%a`" dailyBackup="dailyBackup-`date +%Y%m%d`.tar.gz" weeklyBackup="weeklyBackup-`date +%Y%m%d`.tar.gz" #########begin############### case $Today in Mon|Tue|Wed|Thu|Fri|Sat) echo "`date +'%Y-%m-%d %H:%M:%s'` dailyBackup start" | tee -a $logFile for ((i=1;i<10;i++)) do if [ $i -ge 5 ]; then echo "`date +'%Y-%m-%d %H:%M:%s'` dailyBackupStorage is unavailable!" | tee -a $logFile exit 1 fi cd $dailyBakDIR if [ $? = 0 ]; then break fi sleep 2 done #find $dailyBakDIR -mtime $dailyBakKeeptime -type f -name dailyBackup-\*.gz -exec ls -l {} \; find $dailyBakDIR -mtime $dailyBakKeeptime -type f -name dailyBackup-\*.gz -exec rm -f {} \; tar --exclude $excludeDIR -zcf $dailyBakDIR"/"$dailyBackup $bakDIR &> /dev/null if [ $? = 0 ]; then echo "`date +'%Y-%m-%d %H:%M:%s'` dailyBackup finished" | tee -a $logFile exit 0 fi ;; Sun) echo "`date +'%Y-%m-%d %H:%M:%s'` weeklyBackup start" | tee -a $logFile for ((i=1;i<10;i++)) do if [ $i -ge 5 ]; then echo "`date +'%Y-%m-%d %H:%M:%s'` dailyBackupStorage is unavailable!" | tee -a $logFile exit 1 fi cd $weeklyBakDIR if [ $? = 0 ]; then break fi sleep 2 done #find $weeklyBakDIR -mtime $weeklyBakKeeptime -type f -name weeklyBackup-\*.gz -exec ls -l {} \; find $weeklyBakDIR -mtime $weeklyBakKeeptime -type f -name weeklyBackup-\*.gz -exec rm -f {} \; tar --exclude $excludeDIR -zcf $weeklyBakDIR"/"$weeklyBackup $bakDIR &> /dev/null if [ $? = 0 ]; then echo "`date +'%Y-%m-%d %H:%M:%s'` weeklyBackup finished" | tee -a $logFile exit 0 fi ;; esac ########end######################
注:
– 变量“bakDIR”定义备份的目录为“/data”
– 变量“dailyBakDIR”定义日备的目录为“/databackup/dailyBackup”
– 变量“weeklyBakDIR”定义周备的目录为“/databackup/weeklyBackup”
– 变量“excludeDIR”定义备份排除的目录为“/data/lost+found”
– 变量“logFile”定义备份的日志文件路径为“/var/log/databackup.log”
– 变量“dailyBakKeeptime”定义日备份的保留时间为“+7”,即7天以外的备份数据删除
– 变量“weeklyBakKeeptime”定义周备份的保留时间为“+30”,即30天以外的备份数据删除
2.2.3 创建备份计划任务
crontab -e
加入如下内容
#############################data backup############################### 0 3 * * * sh /root/scripts/databackup.sh
没有评论