建站经验 experience
当前位置:首页 > 网站建设专题 > 建站经验
Dropbox美国主机定时自动备份主机文件到本地
发布日期:2012-06-20 阅读次数:1290 字体大小:

前面介绍过,使用Cpanel空间的时钟守护作业(Cron Jobs)定时备份网站文件到异地服务器,今天来个更高级的,定时把网站文件备份到本地,使用Dropbox完全可以实现。

使用美国主机的朋友,一般都非常熟悉Linux,定时自动执行命令是使用Linux的Cron,Cpanel面板上把它翻译为 时钟守护作业。下面是定时自动备份主机文件到本地的具体步骤:

1、注册Dropbox

Dropbox官网:https://www.dropbox.com

2、登录主机,新建.sh文件

新建backup.sh脚本,复制下面的内容到backup.sh,点击下载脚本。

#!/bin/bash

DROPBOX_USER="Dropbox Email 帐号"

DROPBOX_PASS="Dropbox 密码"

#Dropbox上传目录 默认是dropbox文件夹

DROPBOX_DIR="/dropbox"

#要备份的文件路径

BACKUP_SRC=http://www.webjx.com/webmanage/"/home/myuser/public_html"

#临时目录

BACKUP_DST="/tmp"

MYSQL_SERVER="127.0.0.1"

#mysql用户名

MYSQL_USER="myuser"

#mysql用户密码

MYSQL_PASS="Your MySQL password"

# based on "http://www.***.com/jiaocheng/backup-to-dropbox/"

NOW=$(date +“%Y.%m.%d")

DESTFILE="$BACKUP_DST/$NOW.tgz"

#

# Upload a file to Dropbox.

# $1 = Source file

# $2 = Destination file.

function dropboxUpload

{

#

# Code based on DropBox Uploader 0.6 from http://www.hostjike.com/jiaocheng/backup-to-dropbox/

LOGIN_URL="https://www.dropbox.com/login"

HOME_URL="https://www.dropbox.com/home"

UPLOAD_URL="https://dl-web.dropbox.com/upload"

COOKIE_FILE="/tmp/du_cookie_$RANDOM"

RESPONSE_FILE="/tmp/du_resp_$RANDOM"

UPLOAD_FILE=$1

DEST_FOLDER=$2

# Login

echo -ne "> Logging in.."

curl -s -i -c $COOKIE_FILE -o $RESPONSE_FILE --data "login_email=$DROPBOX_USER&login_password=$DROPBOX_PASS&t=$TOKEN" "$LOGIN_URL"

grep "location: /home" $RESPONSE_FILE > /dev/null

if $? -ne 0 ; then

echo -e " Failed!"

rm -f "$COOKIE_FILE" "$RESPONSE_FILE"

exit 1

else

echo -e " OK"

fi

# Load home page

echo -ne "> Loading Home.."

curl -s -i -b "$COOKIE_FILE" -o "$RESPONSE_FILE" "$HOME_URL"

if $? -ne 0 ; then

echo -e "Failed!"

rm -f "$COOKIE_FILE" "$RESPONSE_FILE"

exit 1

else

echo -e " OK"

fi

# Get token

TOKEN=$(cat "$RESPONSE_FILE" | tr -d '\n' | sed 's/.*

*>\s*

# Upload file

echo -ne "> Uploading '$UPLOAD_FILE' to 'DROPBOX$DEST_FOLDER/'..."

curl -s -i -b $COOKIE_FILE -o $RESPONSE_FILE -F "plain=yes" -F "dest=$DEST_FOLDER" -F "t=$TOKEN" -F :file=@$UPLOAD_FILE" "$UPLOAD_URL"

grep "HTTP/1.1 302 FOUND" "$RESPONSE_FILE">》 /dev/null

if $? -ne 0 ; then

echo -e "Failed!"

rm -f "$COOKIE_FILE" "$RESPONSE_FILE"

exit 1

else

echo -e "OK"

rm -f "$COOKIE_FILE" "$RESPONSE_FILE"

fi

}

#mysql数据库备份

mysqldump -u $MYSQL_USER -h $MYSQL_SERVER -p$MYSQL_PASS --all-databases > "$NOW-Databases.sql"

#压缩

tar cfz "$DESTFILE" $BACKUP_SRC "$NOW-Databases.sql"

#上传

dropboxUpload "$DESTFILE" "$DROPBOX_DIR"

rm -f "$NOW-Databases.sql" "$DESTFILE"

3、修改权限为755,运行backup.sh

如果是虚拟主机,并且开通了SSH,可以使用chmod 755 backup.sh命令修改权限,然后运行backup.sh。

4、使用Cron,定时自动运行backup.sh

Cpanel用户,在时钟守护作业 页面,添加计时程序作业就成!

5、大功告成

到现在,Dropbox就是按你设置的周期,自动将主机上面的文件,备份到本地电脑!