背景:
凡事使用服务器搭建的网站就需要定时备份网站数据,常见的方法是打包网站目录,然后备份到FTP服务器上等。也有通过OSS SDK把备份的网站文件上传到OSS服务器上,但是通过SDK来实现,需要一定的技术能力,而且相对比较复杂,需要使用更多的文件,而这篇文章是通过shell脚本,并不是通过OSS SDK来上传文件,简单方便。
步骤:
1、首先需要在阿里云注册账号,开通OSS服务,创建bucket,Bucket设置为私有读写。
2、将下面的脚本文件复制下来,保存为 .sh 脚本文件(例如:backupsqls,放置在/usr/local/sbin/backupsites),其中需要把oss地址、bucket名字、Access ID、Access Key、网站目录,已经通知邮件的地址修改成自己的。
3、使用命令: chmod +x /usr/local/sbin/backupsqls 对文件设置执行权限。
4、使用命令: echo “0 0 * * * /usr/local/sbin/backupsqls” >>/var/spool/cron/root
设置每天零点进行备份网站数据。
脚本:
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
Date=`date +%Y-%m-%d_%H:%M:%S`
BucketTime=`date +%Y%m`
OldDate=$(date -d "-7 days" "+%Y-%m-%d")
Host="oss-cn-hangzhou-internal.aliyuncs.com"
###oss的地址###
Bucket="bucketname"
###bucket名字###
Id="xxxxxxxx"
###Access ID###
Key="xxxxxxxxxx"
###Access Key###
OssHost=$Bucket.$Host
MYUSER="xxxxx"
MYPASS="xxxxxx"
###备份数据库账号信息###
DBS=`mysql -u$MYUSER -p$MYPASS -P3306 -Bse "show databases" | grep -v "information_schema" | grep -v "test"`
###罗列数据库信息###
#========================BackUp SQL========================
for DateName in $DBS; do
mysqldump --single-transaction -u$MYUSER -p$MYPASS -P3306 $DateName > /tmp/$DateName.$Date.sql
zip -P 密码 /tmp/$DateName.$Date.sql.zip /tmp/$DateName.$Date.sql
###zip压缩设置的密码###
if [ -s /tmp/$DateName.$Date.sql.zip ] ; then
source="/tmp/$DateName.$Date.sql.zip"
dest="$BucketTime/$DateName.$Date.sql.zip"
resource="/${Bucket}/${dest}"
contentType=`file -ib ${source} |awk -F ";" '{print $1}'`
dateValue="`TZ=GMT env LANG=en_US.UTF-8 date +'%a, %d %b %Y %H:%M:%S GMT'`"
stringToSign="PUT\n\n${contentType}\n${dateValue}\n${resource}"
signature=`echo -en $stringToSign | openssl sha1 -hmac ${Key} -binary | base64`
url=http://${OssHost}/${dest}
echo "upload ${source} to ${url}"
curl -i -q -X PUT -T "${source}" \
-H "Host: ${OssHost}" \
-H "Date: ${dateValue}" \
-H "Content-Type: ${contentType}" \
-H "Authorization: OSS ${Id}:${signature}" \
${url}
if [ $? -ne 0 ];then
echo -e ""[$HOSTNAME] DateName $DateName $Date Fail Upload"" | mutt -s "'[$HOSTNAME] DateName $DateName $Date Fail Upload'" [email protected]
else
echo -e ""[$HOSTNAME] DateName $DateName $Date Success"" | mutt -s "'[$HOSTNAME] DateName $DateName $Date Success'" [email protected]
rm -rf /tmp/$DateName.$OldDate*
fi
else
echo -e ""[$HOSTNAME] DateName $DateName $Date Fail Backup "" | mutt -s "'[$HOSTNAME] DateName $DateName $Date Fail Backup'" [email protected]
fi
done
#========================BackUp SQL========================