自动化备份任务总是很有趣的。自动化为使用您的 Linux 服务器来实现您设定的目标提供了巨大的机会。以下示例是我们的备份脚本,名为backup.cron。此脚本旨在通过仅更改以下四个变量在任何计算机上运行
COMPUTER
DIRECTORIES
BACKUPDIR
TIMEDIR
我们建议您在月初首次设置并运行此脚本,然后运行一个月后再进行重大更改。在下面的示例中,我们将备份到本地服务器 BACKUPDIR 上的目录,但是您可以修改此脚本以将其备份到本地服务器上的磁带或通过 NFS 挂载的文件系统。
创建备份脚本backup.cron文件,touch/etc/cron.daily/backup.cron并将以下行添加到此备份文件中
#!/bin/sh # full and incremental backup script # created 07 February 2000 # Based on a script by Daniel O'Callaghan <danny@freebsd.org> # and modified by Gerhard Mourani <gmourani@videotron.ca> #Change the 5 variables below to fit your computer/backup COMPUTER=deep # name of this computer DIRECTORIES="/home" # directoris to backup BACKUPDIR=/backups # where to store the backups TIMEDIR=/backups/last-full # where to store time of full backup TAR=/bin/tar # name and locaction of tar #You should not have to change anything below here PATH=/usr/local/bin:/usr/bin:/bin DOW=`date +%a` # Day of the week e.g. Mon DOM=`date +%d` # Date of the Month e.g. 27 DM=`date +%d%b` # Date and Month e.g. 27Sep # On the 1st of the month a permanet full backup is made # Every Sunday a full backup is made - overwriting last Sundays backup # The rest of the time an incremental backup is made. Each incremental # backup overwrites last weeks incremental backup of the same name. # # if NEWER = "", then tar backs up all files in the directories # otherwise it backs up files newer than the NEWER date. NEWER # gets it date from the file written every Sunday. # Monthly full backup if [ $DOM = "01" ]; then NEWER="" $TAR $NEWER -cf $BACKUPDIR/$COMPUTER-$DM.tar $DIRECTORIES fi # Weekly full backup if [ $DOW = "Sun" ]; then NEWER="" NOW=`date +%d-%b` # Update full backup date echo $NOW > $TIMEDIR/$COMPUTER-full-date $TAR $NEWER -cf $BACKUPDIR/$COMPUTER-$DOW.tar $DIRECTORIES # Make incremental backup - overwrite last weeks else # Get date of last full backup NEWER="--newer `cat $TIMEDIR/$COMPUTER-full-date`" $TAR $NEWER -cf $BACKUPDIR/$COMPUTER-$DOW.tar $DIRECTORIES fi |
示例 33-1。一周的备份目录
这是一周后备份目录的简略视图
[root@deep] /# ls -l /backups/ |
total 22217 -rw-r--r-- 1 root root 10731288 Feb 7 11:24 deep-01Feb.tar -rw-r--r-- 1 root root 6879 Feb 7 11:24 deep-Fri.tar -rw-r--r-- 1 root root 2831 Feb 7 11:24 deep-Mon.tar -rw-r--r-- 1 root root 7924 Feb 7 11:25 deep-Sat.tar -rw-r--r-- 1 root root 11923013 Feb 7 11:24 deep-Sun.tar -rw-r--r-- 1 root root 5643 Feb 7 11:25 deep-Thu.tar -rw-r--r-- 1 root root 3152 Feb 7 11:25 deep-Tue.tar -rw-r--r-- 1 root root 4567 Feb 7 11:25 deep-Wed.tar drwxr-xr-x 2 root root 1024 Feb 7 11:20 last-full |
: 存储备份的目录BACKUPDIR,以及存储完整备份时间的目录TIMEDIR必须在使用备份脚本之前存在或创建,否则您将收到错误消息。
如果您不是从月初 01-month-year 开始运行此备份脚本,则增量备份将需要星期日备份的时间才能正常工作。如果您在一周的中间开始,则需要在TIMEDIR中创建时间文件。TIMEDIR目录中创建时间文件,请使用以下命令
[root@deep] /# date +%d%b < /backups/last-full/myserver-full-date |
使此脚本可执行,并将其默认权限更改为仅超级用户可写root 755.
[root@deep] /# chmod 755 /etc/cron.daily/backup.cron |
: 因为此脚本位于/etc/cron.daily目录中,它将每天凌晨一点自动作为 cron 作业运行。