目录

通常我们需要在线上的linux服务器上定时备份一些目录或文件(可能是代码或日志或配置),我们一般会考虑使用crond来实现定期计划任务。

1、至于备份我们可以写一个shell脚本:

比如百度的某个重要配置文件在我们手上, 我们要定期去做备份/etc/baidu/config/,并忽略其中的logs目录下的文件,然后再将一个月以前的备份的gz文件删除:

#!/bin/sh
rq=`date +%Y%m`
nf=/data/backup/www.baidu.com-$rq.tar.gz
tar zcvf $nf --exclude=/etc/baidu/config/logs  /etc/baidu/config/
if [ ! -f $nf ]; then
exit 0
fi
echo $nf

ef=/data/backup/www.baidu.com-`date -d '-1 months' +%Y%m`.tar.gz
if [ -f "$ef" ]; then
rm -f $ef
echo $ef
fi

2、除了shell去实现备份,我们也可以采用php进行备份:

备份mysql导出的数据库数据、nginx配置文件、所有指定代码目录(可指定去除文件)

/**
 * 定期备份文件
 * how to use: 
 * crontab -e
 * #每周五3:30
  30 3 * * 5  /usr/bin/php -f crontab/backup.php 1>>backup.log 2>>backup.error
 */	

error_reporting(E_ALL);
define("IS_ONLINE", true); //为false则不生成文件,只输出命令用于测试命令是否正常
	
echo "定期备份*.*.xx.xx数据开始:\t" . date("Y-m-d H:i:s", time()) . "\n";
$backupObj = new Backup();
$backupObj->backupDatabase();
$backupObj->backupNginxConfig();
$backupObj->backCodes();
$message = "*.*.xx.xx上于" . date("Y-m-d H:i:s") .
        "自动备份数据库" . print_r($backupObj->databaseArray, true) .
        ",自动备份" . $backupObj->nginx_config_dir . "下所有nginx配置文件.";
$backupObj->send_mail($message);
echo "结束定期备份*.*.xx.xx数据:\t" . date("Y-m-d H:i:s", time()) . "\n";

/**
 * backup class
 */
class Backup {

    /**
     * 项目目录名
     * @var type 
     */
    public $allCodePathArray = array("www.baidu.com", "www.tencent.com", "www.china.com", "www.shanyang.com", "www.php.net");

    /**
     * 数据库名
     * @var type 
     */
    public $databaseArray = array('db1', 'db2', 'db3', 'db4');

    /**
     * nginx配置目录
     * @var type 
     */
    public $nginx_config_dir = '/etc/nginx/sites-enabled/';
    public $database_host = '127.0.0.1';
    public $database_username = 'username';
    public $database_password = 'pwdddddd';
    public $allBackupDbFiles = array();

    public function __construct() {
        
    }

    /**
     * 数据库备份
     */
    public function backupDatabase() {
        $allBackupDbFiles = array();
        $databaseArray = $this->databaseArray;
        echo "开始备份数据库文件:\n";
        foreach ($databaseArray as $database) {
            $backup_file = "/data/backup/" . $database . "." . ".sql";
            if (is_file($backup_file)) {
                unlink($backup_file);
                echo "unlink " . $backup_file . "\n";
            }
            $command = '/usr/bin/mysqldump -h ' . $this->database_host . ' -u' . $this->database_username . ' -p' . $this->database_password . ' ' . $database . ' > ' . $backup_file;
            echo $command . "\n";
            if (IS_ONLINE) {
                $res = exec($command);
            }
            $allBackupDbFiles[] = $backup_file;
        }
        $this->allBackupDbFiles = $allBackupDbFiles;
        echo "=============================================\n";
        print_r($allBackupDbFiles);
        echo "=============================================\n";
        echo "数据库备份完成.\n";
    }

    /**
     * nginx配置文件备份
     */
    public function backupNginxConfig() {
        $backup_nginx_error = '';
        $nginx_config_dir = $this->nginx_config_dir;
        echo "开始备份nginx配置文件:\n";
        if (file_exists($nginx_config_dir)) {
            if ($handle = opendir($nginx_config_dir)) {
                while (false !== ($file = readdir($handle))) {
                    if ($file != "." && $file != "..") {
                        $backup_nginx_dir = "/data/backup/nginx/";
                        if (!file_exists($backup_nginx_dir)) {
                            mkdir($backup_nginx_dir, 0755, true);
                        }
                        $backup_nginx_file = $backup_nginx_dir . $file;
                        $content = file_get_contents($nginx_config_dir . $file);
                        file_put_contents($backup_nginx_file, $content);
                        echo $nginx_config_dir . $file . "\t=>\t" . $backup_nginx_file . "\n";
                    }
                }
                closedir($handle);
            } else {
                $backup_nginx_error .= "#" . $nginx_config_dir . " open failed.\n";
            }
        } else {
            $backup_nginx_error .= "#" . $nginx_config_dir . " is not exixts.\n";
        }
        echo $backup_nginx_error;
        echo "完成nginx配置文件备份.\n";
    }

    public function backCodes() {
        $backDir = $this->allCodePathArray;
        echo "开始备份代码目录文件:\n";
        foreach ($backDir as $one) {
            $excludeCommand = '';
            $src = "/var/www/html/" . $one . "/";
            $desc = "/data/backup/" . $one . ".tar.gz";
            if (is_file($desc)) {
                unlink($desc);
                echo "unlink " . $desc . "\n";
            }
            if (file_exists($src) && is_dir($src)) {	                
                $excludeCommand = "--exclude=" . $src . "logs/";	               
                $command = "tar jcvf " . $desc . " " . $excludeCommand . $src;
                echo $command . "\n";
                if (IS_ONLINE) {
                    $res = exec($command);
                }
            }
        }
        echo "完成项目代码文件备份.\n";
    }

    /**
     * sendmail
     * @param type $message
     */
    public function send_mail($message = '') {
        if (!IS_ONLINE) {
            return false;
        }
        $from = "From Server aliyun *.*.xxx.xxx";
        $to = 'jm@shanyang.com';
        $subject = "=?UTF-8?B?" . base64_encode("数据库/Nginx配置/项目文件已经备份,等待上传到七牛云存储") . "?="; //中文主题处理

        /**
         * 中文header处理
         */
        $headers = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
        $headers .= 'From: ' . $from . "\r\n" . 'Reply-To: ' . $from;

        mail($to, $subject, $message, $headers);
    }

}

3、备份好的文件如何备份到云端

有很多云端服务,这里举例七牛的同步工具:

七牛qrsync同步 详见《七牛qrsync 命令行同步工具》


@tsingchan 2015