备份 Wordpress 到 Amazon AWS S3

/

Wordpress 备份插件很多,比如著名的 BackupBuddy,能够很方便的备份到 Amazon AWS S3 等云端,不过如果需求比较简单,完全可以自己写一个备份脚本。

首先,安装 Amazon 命令行工具。

wget https://s3.amazonaws.com/aws-cli/awscli-bundle.zip
unzip awscli-bundle.zip
sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws
aws configure
#  将会提示输入 access key、secret access key、default region、format 4项
#  access key、secret access key 在 IAM 管理页可以得到
#  default region、format 默认是空的,也可以根据需要设置成其它内容

以下是脚本内容,将 Wordpress 数据库和整个站点(排除个别目录)备份到站点所在服务器,同时将备份内容同步到Amazon AWS S3(本地没有云端有的内容在云端会被删除)。

# !/bin/bash
if (( ${EUID} )); then
    echo "This script must be run as root!"
    exit 1
fi

siteDir=/var/www/example.com
exclude="dir1 dir2 dir3 wp-content/uploads"
backupDir=/var/www/_backups
date=$(date +%Y%m%d%H%M)
bucket=bucketname

host=$(grep DB_HOST ${siteDir}/wp-config.php | cut -d "'" -f 4)
user=$(grep DB_USER ${siteDir}/wp-config.php | cut -d "'" -f 4)
password=$(grep DB_PASSWORD ${siteDir}/wp-config.php | cut -d "'" -f 4)
db=$(grep DB_NAME ${siteDir}/wp-config.php | cut -d "'" -f 4)

if [[ ! -d ${backupDir} ]]; then
    mkdir -p ${backupDir}
    chown www-data:www-data ${backupDir}
fi

#  export database
mysqldump -u $user -p${password} $db | gzip > ${backupDir}/db_${siteDir##*/}_${date}.gz
if (( $? )); then
    echo "export database failed!"
    exit 1
else
    echo "export database done!"
fi

#  export files
tar -czf ${backupDir}/site_${siteDir##*/}_${date}.tar.gz -X <(for i in ${exclude}; do echo ${siteDir##*/}/$i; done) -C ${siteDir%/*} ${siteDir##*/}
if (( $? )); then
    echo "export files failed!"
    exit 1
else
    echo "export files done!"
fi

#  remove older backups
find ${backupDir}/site* -mtime +1 -exec rm {} \;
find ${backupDir}/db* -mtime +7 -exec rm {} \;
if (( $? )); then
    echo "remove older backups failed!"
    exit 1
else
    echo "remove older backups done!"
fi

#  sync to amazon
/usr/local/bin/aws s3 sync ${backupDir} s3://${bucket} --delete
if (( $? )); then
    echo "sync to amazon failed!"
    exit 1
else
    echo "sync to amazon done!"
fi

最后选择合适的用户建立 cron 任务,定期执行上述脚本即可。

Comments