自动定时加密备份网站数据并上传到其它FTP空间的shell脚本
以下为详细的脚本代码,保存成backup.sh,并根据下面的说明配置即可使用
#!/bin/bash
#为backup.sh添加执行权限chmod +x /root/backup.sh
#添加脚本至crontab(自动启动程序)执行命令crontab -e,添加每天0点10分启动代码
#10 00 * * * /root/backup.sh
#===========配置区开始==============
BACKUP_DATA_TEMP="/home/backup"
DB_USR="数据库用户名"
DB_PWD="数据库密码"
FTP_HOST="FTP主机名"
FTP_USR="FTP用户名"
FTP_PWD="FTP密码"
ZIP_PWD="压缩包密码"
#数据库文件位置
DB_PATH="/home/mysql_data"
#网站数据文件位置
WEB_PATH="/home/ftp/1520"
#其它要备份的文件夹
OTHER_PATH="/home/lum_safe_files"
#按周清理,设为0则按天清理
ROUND_WEEK="1"
#===========配置区结束==============
FTP_FOLDER=$(date +"%Y-%m-%d")
if [ ROUND_WEEK = 1 ];then
OLD_FTP_FOLDER=$(date -d -3week +"%Y-%m-%d")
else
OLD_FTP_FOLDER=$(date -d -3day +"%Y-%m-%d")
fi
#在FTP空间里新建目录
ftp -v -n $FTP_HOST <<END
user $FTP_USR $FTP_PWD
type binary
prompt off
cd public_html
mkdir $FTP_FOLDER
ls . temp_ftpdir.txt
bye
END
mkdir $BACKUP_DATA_TEMP
cd $BACKUP_DATA_TEMP
#========压缩其它文件========
zip -9 -q -r -P $ZIP_PWD $BACKUP_DATA_TEMP/lum_safe_files.zip $OTHER_PATH/
#上传到FTP空间
ftp -v -n $FTP_HOST <<END
user $FTP_USR $FTP_PWD
type binary
cd public_html
cd $FTP_FOLDER
put lum_safe_files.zip
bye
END
rm -rf $BACKUP_DATA_TEMP/lum_safe_files.zip
#===========导出mysql数据库===========
DBLIST=`ls -p $DB_PATH | grep / | tr -d /`
for dbname in $DBLIST
do
#mysqldump -u $DB_USR -p$DB_PWD $dbname > $BACKUP_DATA_TEMP/$dbname.sql
mysqlhotcopy $dbname -u $DB_USR -p $DB_PWD $BACKUP_DATA_TEMP | logger -t mysqlhotcopy
#压缩数据库
zip -9 -q -r -P $ZIP_PWD $BACKUP_DATA_TEMP/$dbname.mysql.zip $BACKUP_DATA_TEMP/$dbname/
#删除sql文件
rm -rf $BACKUP_DATA_TEMP/$dbname/
#上传到FTP空间
ftp -v -n $FTP_HOST <<END
user $FTP_USR $FTP_PWD
type binary
cd public_html
cd $FTP_FOLDER
put $dbname.mysql.zip
bye
END
rm -rf $BACKUP_DATA_TEMP/$dbname.mysql.zip
done
#==========压缩网站数据=============
DBLIST=`ls -p $WEB_PATH | grep / | tr -d /`
for dbname in $DBLIST
do
zip -9 -q -r -P $ZIP_PWD $BACKUP_DATA_TEMP/$dbname.page.zip $WEB_PATH/$dbname
#上传到FTP空间
ftp -v -n $FTP_HOST <<END
user $FTP_USR $FTP_PWD
type binary
cd public_html
cd $FTP_FOLDER
put $dbname.page.zip
bye
END
rm -rf $BACKUP_DATA_TEMP/$dbname.page.zip
done
if [ -f "temp_ftpdir.txt" ] && [ `cat temp_ftpdir.txt | awk '{print $9}' | grep $OLD_FTP_FOLDER | wc -l` -ge 1 ];then
#删除FTP空间5天前的数据
ftp -v -n $FTP_HOST <<END
user $FTP_USR $FTP_PWD
type binary
cd public_html
cd $OLD_FTP_FOLDER
prompt off
mdelete *.*
cd ../
rmdir $OLD_FTP_FOLDER
bye
END
rm -rf temp_ftpdir.txt
fi
#删除本地的备份数据
rm -rf $BACKUP_DATA_TEMP/
代码到上面就结束了
然后添加自动执行crontab -e
添加一行,内容为:
10 00 * * * /root/backup.sh
- 最新评论