PHP头条
热点:

MySQL备份脚本,mysql脚本


mysqlbackup.php:

<?php

    //备份mysql
    
    set_time_limit(0);
    date_default_timezone_set('PRC');
    
    //配置
    $configs = array(
        'host1'=>array(
            'localhost',
            'root',
            'root',
            array(),  //为空备份全部数据库,否则备份这些数据库
            'D:/xampp/mysql/bin/mysqldump',    //备份工具
            dirname(__FILE__)."/localhost",  //目录加主机名
            5,  //删除前5天的SQL文件
        ),);

    foreach($configs as $config) {
        $logsfile = $config[5].'/'.date('ymd').'.log';
        logs($logsfile, $config[0]." backup\n");
        backup($config);
    }

    function backup($config) {
        list($host, $username, $password, $databases, $backuptool, $backupdir, $day) = $config;
        $command = "$backuptool -u $username -h $host -p$password %s > %s";  
        $logsfile = $backupdir.'/'.date('ymd').'.log';
        $backfilename = $backupdir.'/'.date('Ymd')."%s.sql";   //备份的SQL文件,以数据库命名
        
        if(!is_dir($backupdir)) {
            mkdir($backupdir, 0755 , true); 
        }
        
        //删除前十天的备份文件
        get_dir_files($backupdir, $returnval);
        if($returnval) {
            foreach($returnval as $v) {
                $time = filemtime($v);
                if($time < strtotime("-$day day") && (pathinfo($v,PATHINFO_EXTENSION))=='zip') {
                    unlink($v);
                }
            }
        }
        
        if(!$databases) {
            $databases = getdatabases($host, $username, $password);
        }

        //开始备份
        foreach($databases as $database) {
            $outputfile = sprintf($backfilename, $database);
            $execcommand = sprintf($command, $database, $outputfile);

            try {
                if(system($execcommand) === false) {
                    throw new Exception('execute backup command error!');
                }
                
                //文件过大时会压缩失败(测试的那个SQL文件4.62G,压缩失败,没创建那个压缩文件。测试2.81G可以)
                if(file_exists($outputfile)) {
                    $zip = new ZipArchive();
                    $filename = pathinfo($outputfile,PATHINFO_FILENAME);
                    $zipname = $backupdir.'/'.$filename.'.zip';  //zip文件的路径
                    if($zip->open($zipname, ZIPARCHIVE::OVERWRITE) === true) {
                        $zip->addFile($outputfile, $filename.'.'.pathinfo($outputfile,PATHINFO_EXTENSION));
                        
                        $zip->close();
                    }else {
                        throw new Exception('ZipArchive open error!');
                    }
                }
                
                if(!file_exists($zipname) || (filesize($zipname)==0)) {
                    throw new Exception('ZipArchive create error!');
                }
                
                $message = date('Y-m-d H:i:s')."$database backup complete!\r\n";
                logs($logsfile, $message);
            }catch(Exception $e) {
                $message = date('Y-m-d H:i:s').$e->getLine().' '.$e->getMessage()."\r\n";
                logs($logsfile, $message);
            }

        }
    }

    function getdatabases($host, $username, $password) {
        $databases = array();
        
        try {
            $mysqli = new Mysqli($host, $username, $password);
            $result = $mysqli->query("show databases");
            if($result) {
                while($row = $result->fetch_row()) {
                    (current($row)!='information_schema' && current($row)!='mysql' && current($row)!='performance_schema') && $databases[] = current($row);
                }
                $result->free_result();
                $mysqli->close();
            }else {
                throw new Exception('No databases!');
            }
        }catch(Exception $e) {
            $message = date('Y-m-d H:i:s').$e->getLine().' '.$e->getMessage()."\r\n";
            logs($logsfile, $message);
        }    
        
        return $databases;
    }
    
    function logs($file, $contents) {
        $dirname = dirname($file);
        try {
            if(!is_dir(dirname($file)) || !is_writeable(dirname($file))) {
                throw new Exception("file is not direcotory or file can't write");
            }
            file_put_contents($file, $contents, FILE_APPEND);
        }catch(Exception $e) {
            $message = date('Y-m-d H:i:s').$e->getLine.' '.$e->getMessage()."\r\n";
            logs($logfile, $message);
        }
    }
    
    
    //获取当前目录下的文件(不包含子文件夹)
    function get_dir_files($currPath, &$returnVal=array()) {
        if(is_dir($currPath)) {
            $currPath = (substr($currPath,-1,1)=='/')?substr($currPath,0,strlen($currPath)-1):$currPath;

            if($handler = opendir($currPath)) {
                while(($fileName = readdir($handler)) !== false) {
                    if($fileName != '.' && $fileName != '..' && $fileName[0] != '.') {
                        if(is_file($currPath . '/' . $fileName)) {
                            $returnVal[] = $currPath . '/' . $fileName;
                        }
                    }
                }
                closedir($handler);
            }
        }
    }
?>

 

mysqlbackup.bat:

D:\xampp\php\php.exe -q D:\wamp\www\php_lib\basic\mysqlbackup.php
pause;

linux系统shell备份MySQL:

#!/bin/sh
# sed -i 's/^M//g' /home/taskschd/backup.sh
#注意:^M的输入方式是 Ctrl + v ,然后Ctrl + M
dbs=(test)
ROOT_DIR=/home/backup/
for dbname in ${dbs[@]}
 do
  #备份数据
  BACKUP_DIR=$ROOT_DIR$dbname'_'$(date +%Y%m%d).sql
  /usr/local/mysql/bin/mysqldump --opt -uroot -pabc $dbname > $BACKUP_DIR
  #删除三天前数据
  delete_file=$dbname'_'$(date -d "-5 day" "+%Y%m%d")'.sql'  
  rm $ROOT_DIR$delete_file  
 done

另为一篇shell备份mysql脚本:http://www.cnblogs.com/luoyunshu/p/3435378.html


linux系统下mySQL数据库 备份方法与脚本?

方法一、适合所有格式的mysql数据库,通过对数据库导出导进写个脚本定时执行:
1.导出整个数据库 mysqldump -u 用户名 -p 数据库名 > 导出的文件名 mysqldump -u wcnc -p smgp_apps_wcnc > /存放路径/wcnc.sql
2.导出一个表 mysqldump -u 用户名 -p 数据库名 表名> 导出的文件名 mysqldump -u wcnc -p smgp_apps_wcnc users> /存放路径/wcnc_users.sql
3.导出一个数据库结构 mysqldump -u wcnc -p -d --add-drop-table smgp_apps_wcnc >/存放路径/wcnc_db.sql
定义:
-d 没有数据
--add-drop-table 在每个create语句之前增加一个drop table
4.导入数据库 常用source 命令 进入mysql数据库控制台:
如mysql -u root -p mysql>use 数据库

方法二、针对mysql数据表格式为MyISAM的
假如数据文件在/var/lib/mysql
那么直接写个脚本
cp -r /var/lib/mysql /备份到的文件夹路径

隔机备份用rsync增量,或定时完整备份。
 

谁可以给我一个MYSQL自动备份的脚本

可能是你不会用吧

可以将这个脚本放进crontab,每天凌晨执行一次,自动备份

这个脚本每天最多只执行一次,而且只保留最近五天的备份在服务器上。

代码:

#!/bin/bash
#This is a ShellScript For Auto DB Backup
#Powered by aspbiz
#2004-09

#Setting
#设置数据库名,数据库登录名,密码,备份路径,日志路径,数据文件位置,以及备份方式
#默认情况下备份方式是tar,还可以是mysqldump,mysqldotcopy
#默认情况下,用root(空)登录mysql数据库,备份至/root/dbxxxxx.tgz
DBName=mysql
DBUser=root
DBPasswd=
BackupPath=/root/
LogFile=/root/db.log
DBPath=/var/lib/mysql/
#BackupMethod=mysqldump
#BackupMethod=mysqlhotcopy
#BackupMethod=tar
#Setting End

NewFile="$BackupPath"db$(date +%y%m%d).tgz
DumpFile="$BackupPath"db$(date +%y%m%d)
OldFile="$BackupPath"db$(date +%y%m%d --date='5 days ago').tgz

echo "-------------------------------------------" >> $LogFile
echo $(date +"%y-%m-%d %H:%M:%S") >> $LogFile
echo "--------------------------" >> $LogFile
#Delete Old File
if [ -f $OldFile ]
then
rm -f $OldFile >> $LogFile 2>&1
echo "[$OldFile]Delete Old File Success!" >> $LogFile
else
echo "[$OldFile]No Old Backup File!" >> $LogFile
fi

if [ -f $NewFile ]
then
echo "[$NewFile]The Backup File is exists,Can't Backup!" >> $LogFile
else
case $BackupMethod in
mysqldump)
if [ -z $DBPasswd ]
then
mysqldump -u $DBUser --opt $DBName > $DumpFile
else
mysqldump -u $DBUser -p$DBPasswd --opt $DBName > $DumpFile
f......余下全文>>
 

www.phpzy.comtrue/php/12271.htmlTechArticleMySQL备份脚本,mysql脚本 mysqlbackup.php: ? php // 备份mysql set_time_limit (0 ); date_default_timezone_set( 'PRC' ); // 配置 $configs = array ( 'host1'= array ( 'localhost', 'root', 'root', array (), // 为空备份全部数据库...

相关文章

相关频道:

PHP之友评论

今天推荐