很实用,收藏好。
#!/bin/bash
#功能:自动备份网站及mysql 自动删除本地及ftp3天前的备份
#更多:http://www.ptcms.com/product-linux.html
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
#备份设置
MYSQL_USER=root #mysql用户
MYSQL_PASS=root #mysql密码
WEB_DATA=/home/wwwroot #网站根目录
FTP_IP=127.0.0.1 #远程FTP地址
FTP_USER=backup #远程FTP用户
FTP_PASS=backup #远程FTP密码
FTP_backup=/backup #远程FTP目录
MAIL_TO=backup@gmail.com #接收mysql邮件
#设置备份名及备份目录
DataBakName=Data_$(date +"%Y%m%d").tar.gz #数据库备份名
WebBakName=Web_$(date +%Y%m%d).tar.gz #网站备份名
OldFTPData=Data_$(date -d -3day +"%Y%m%d").tar.gz
OldFTPWeb=Web_$(date -d -3day +"%Y%m%d").tar.gz
OldLOCData=Data_$(date -d -1day +"%Y%m%d").tar.gz
OldLOCWeb=Web_$(date -d -1day +"%Y%m%d").tar.gz
#删除本地之前的备份
rm -rf /home/backup/$OldLOCData
rm -rf /home/backup/$OldLOCWeb
cd /home/backup
#备份mysql
for db in `mysql -u$MYSQL_USER -p$MYSQL_PASS -B -N -e 'SHOW DATABASES' | xargs`;
do
if [ $db != "information_schema" ] && [ $db != "mysql" ];then
(/usr/local/mysql/bin/mysqldump -uroot -pPTcms.com ${db} --skip-lock-tables > ${db}.sql)
fi
done
#压缩打包mysql
tar zcf $DataBakName *.sql
rm -rf *.sql
#压缩打包网站
tar zcf $WebBakName $WEB_DATA
#数据上传至ftp
ftp -v -n $FTP_IP << END
user $FTP_USER $FTP_PASS
type binary
cd $FTP_backup
delete $OldFTPData
delete $OldFTPWeb
put $DataBakName
put $WebBakName
bye
END
#以附件方式把数据发送给邮箱
echo "MySQL Data backup on $(date +"%Y-%m-%d") at $(date +"%T")" | mutt -a /home/backup/$DataBakName -s "MySQL Data Backup $(date +"%Y-%m-%d")" $MAIL_TO