mysql[1] 邏輯卷備份mysqldump

今天就和你們聊聊mysqldump備份工具:python


mysqldumpmysql

  • MySQL數據庫自帶的一款(邏輯)備份工具;linux

  • 可以對數據庫、表、觸發器、存儲過程、事件等備份;sql

  • 備份的文件是可執行的sql語句純文本文件中。數據庫


mysqldump engines
bash

  • 對MyISAM存儲引擎進行溫備,必須加參數--lock-all-tables服務器

  • 對InnoDB存儲引擎進行熱備,必須加參數--single-transactionsession


mysqldump usageapp

一、備份單個數據庫和單個數據庫下的某些表ide

    mysqldump [OPTIONS] database [tables]

二、備份多個數據庫

    mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]

三、備份全部數據庫

    mysqldump [OPTIONS] --all-databases [OPTIONS]


mysqldump的可選參數不少,這裏只說比較經常使用的參數:

   --master-data[=#]

該選項將binlog的位置和文件名追加到輸出文件中;
該選項有三個可選值:0、一、2

0:不記錄二進制日誌文件及路位置
1:以CHANGE MASTER TO的方式記錄位置,可用於恢復後直接啓動從服務器
2:以CHANGE MASTER TO的方式記錄位置,但默認被註釋

   --flush-logs

在開始dump以前刷新二進制日誌

   --single-transaction

適合InnoDB存儲引擎(不適用MyISAM),此選項與--lock-tables選擇是互斥的,由於lock tables會使任何掛起的事務隱含提交;要想提交大表的話,應結合使用--quick選項

若是指定庫中的表類型均爲InnoDB,可以使用--single-transaction自動熱備
注意:--single-transaction不要和--lock-all-tables一塊兒使用,--single-transaction會中實加鎖

    --lock-all-tables

提交請求鎖定全部數據庫中的全部表,以保證數據的一致性。這是一個全局讀鎖,而且自動關閉--single-transaction 和--lock-tables 選項。

    --events

導出事件調度器

    --triggers 

導出觸發器

     --routines 

導出存儲過程以及自定義函數

    --quick

不緩衝查詢,直接導出到標準輸出。默認爲打開狀態,使用--skip-quick取消該選項

    --no-create-db 

若是導出數據庫的時候,使用--all-databases或--databases這兩個選項,則表示只導出數據,而不添加CREATE DATABASE語句。

     --no-create-info

只導出數據,而不添加CREATE TABLE 語句。

     --no-data

不導出任何數據,只導出數據庫表結構。



mysqldump的備份策略:

  • 徹底備份 + 增量備份(相對於差別備份節約磁盤空間)

  • 徹底備份 + 差別備份(相對於增量備份恢復時間短)


概念

  • 徹底備份:備份所有數據庫

  • 增量備份:僅備份上次徹底備份或增量備份之後變化的數據

  • 差別備份:僅備份上次徹底備份以來變化的數據


前面提過mysqldump對MyISAM存儲引擎溫備,對InnoDB存儲引擎熱備:

多種方式查看錶的存儲引擎:

方式一:

mysql> select TABLE_NAME,ENGINE from information_schema.tables where table_schema='數據庫';
mysql> select TABLE_NAME,ENGINE from information_schema.tables where table_schema='mysql';
+---------------------------+--------+
| TABLE_NAME                | ENGINE |
+---------------------------+--------+
| columns_priv              | MyISAM |
| db                        | MyISAM |
| event                     | MyISAM |
| func                      | MyISAM |
| general_log               | CSV    |
| help_category             | MyISAM |
| help_keyword              | MyISAM |
| help_relation             | MyISAM |
| help_topic                | MyISAM |
| host                      | MyISAM |
| ndb_binlog_index          | MyISAM |
| plugin                    | MyISAM |
| proc                      | MyISAM |
| procs_priv                | MyISAM |
| proxies_priv              | MyISAM |
| servers                   | MyISAM |
| slow_log                  | CSV    |
| tables_priv               | MyISAM |
| time_zone                 | MyISAM |
| time_zone_leap_second     | MyISAM |
| time_zone_name            | MyISAM |
| time_zone_transition      | MyISAM |
| time_zone_transition_type | MyISAM |
| user                      | MyISAM |
+---------------------------+--------+


方式二:

mysql> show table status from 數據庫 where name='表名';
mysql> show table status from mysql where name='user';
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------+----------+----------------+-----------------------------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time         | Update_time         | Check_time | Collation | Checksum | Create_options | Comment                     |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------+----------+----------------+-----------------------------+
| user | MyISAM |      10 | Dynamic    |    4 |             53 |         212 | 281474976710655 |         2048 |         0 |           NULL | 2015-03-05 21:34:03 | 2015-03-05 21:34:04 | NULL       | utf8_bin  |     NULL |                | Users and global privileges |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------+----------+----------------+-----------------------------+
1 row in set (0.00 sec)


方式三:

mysql> show create table 表名;
| user  | CREATE TABLE `user` (
  `Host` char(60) COLLATE utf8_bin NOT NULL DEFAULT '',
  `User` char(16) COLLATE utf8_bin NOT NULL DEFAULT '',
  `Password` char(41) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL DEFAULT '',
  `Select_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Insert_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Update_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Delete_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Drop_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Reload_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Shutdown_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Process_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `File_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Grant_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `References_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Index_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Alter_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Show_db_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Super_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_tmp_table_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Lock_tables_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Execute_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Repl_slave_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Repl_client_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_view_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Show_view_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_routine_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Alter_routine_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_user_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Event_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Trigger_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `Create_tablespace_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
  `ssl_type` enum('','ANY','X509','SPECIFIED') CHARACTER SET utf8 NOT NULL DEFAULT '',
  `ssl_cipher` blob NOT NULL,
  `x509_issuer` blob NOT NULL,
  `x509_subject` blob NOT NULL,
  `max_questions` int(11) unsigned NOT NULL DEFAULT '0',
  `max_updates` int(11) unsigned NOT NULL DEFAULT '0',
  `max_connections` int(11) unsigned NOT NULL DEFAULT '0',
  `max_user_connections` int(11) unsigned NOT NULL DEFAULT '0',
  `plugin` char(64) COLLATE utf8_bin DEFAULT '',
  `authentication_string` text COLLATE utf8_bin,
  PRIMARY KEY (`Host`,`User`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Users and global privileges' |

方式四:

# mysqlshow -uroot -p --status 數據庫名字 表名(不加表名查看全部的)
[root@localhost ~]# mysqlshow -uroot -p --status mysql user;
Enter password: 
Database: mysql  Wildcard: user
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------+----------+----------------+-----------------------------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time         | Update_time         | Check_time | Collation | Checksum | Create_options | Comment                     |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------+----------+----------------+-----------------------------+
| user | MyISAM | 10      | Dynamic    | 4    | 53             | 212         | 281474976710655 | 2048         | 0         |                | 2015-03-05 21:34:03 | 2015-03-05 21:34:04 |            | utf8_bin  |          |                | Users and global privileges |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------+----------+----------------+-----------------------------+


查看數據庫所支持的存儲引擎

mysql> show engines;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                        | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| MRG_MYISAM         | YES     | Collection of identical MyISAM tables                          | NO           | NO   | NO         |
| InnoDB             | DEFAULT | Supports transactions, row-level locking, and foreign keys     | YES          | YES  | YES        |
| CSV                | YES     | CSV storage engine                                             | NO           | NO   | NO         |
| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears) | NO           | NO   | NO         |
| MyISAM             | YES     | MyISAM storage engine                                          | NO           | NO   | NO         |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                             | NO           | NO   | NO         |
| ARCHIVE            | YES     | Archive storage engine                                         | NO           | NO   | NO         |
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables      | NO           | NO   | NO         |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
8 rows in set (0.00 sec)


修改現有表的存儲引擎

mysql> use mydb;
Database changed
mysql> show create table tutor;
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                              |
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tutor | CREATE TABLE `tutor` (
  `TID` int(11) DEFAULT NULL,
  `Tname` char(20) DEFAULT NULL,
  `Gender` char(10) DEFAULT NULL,
  `Age` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> alter table tutor engine=innodb;
Query OK, 9 rows affected (0.15 sec)
Records: 9  Duplicates: 0  Warnings: 0

mysql> show create table tutor;
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                              |
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tutor | CREATE TABLE `tutor` (
  `TID` int(11) DEFAULT NULL,
  `Tname` char(20) DEFAULT NULL,
  `Gender` char(10) DEFAULT NULL,
  `Age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+-------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)


基於二進制日誌能夠對MySQL數據庫作完整性恢復

  • 查看是否開啓二進制日誌

mysql> show global variables like '%log_bin%';
+---------------------------------+-------+
| Variable_name                   | Value |
+---------------------------------+-------+
| log_bin                         | ON    |
| log_bin_trust_function_creators | OFF   |
| sql_log_bin                     | ON    |
+---------------------------------+-------+
3 rows in set (0.00 sec)
  • 刷新二進制日誌、查看當前使用的二進制日誌文件和所處的偏移位Position

mysql> flush logs;
Query OK, 0 rows affected (0.01 sec)

mysql> show master status;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000005 |      107 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
  • 向數據庫插入數據、刪除數據、創建受權用戶

mysql> use mydb;
mysql> show tables;
+----------------+
| Tables_in_mydb |
+----------------+
| tutor          |
+----------------+
1 row in set (0.00 sec)

mysql> insert into tutor values(10,'huojianhua','M',32);
Query OK, 1 row affected (0.00 sec)

mysql> insert into tutor values(11,'luozhixiang','M',35);
Query OK, 1 row affected (0.00 sec)

mysql> delete from tutor where TID=10;
Query OK, 1 row affected (0.00 sec)

mysql> grant select on mydb.tutor to 'zhengyansheng'@'192.168.10.15' identified by 'password';
Query OK, 0 rows affected (0.00 sec)
  • 再次查看二進制日誌文件所處的偏移位Position

mysql> show master status;    #Position發生變化
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000005 |      313 |              |                  |    
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
  • 查看二進制日誌事件信息(不能看到命令的執行時間)

mysql> show binlog events in 'mysql-bin.000005';
+------------------+-----+-------------+-----------+-------------+----------------------------------------------------------------------------------------------------+
| Log_name         | Pos | Event_type  | Server_id | End_log_pos | Info                                                                                               |
+------------------+-----+-------------+-----------+-------------+----------------------------------------------------------------------------------------------------+
| mysql-bin.000005 |   4 | Format_desc |         1 |         107 | Server ver: 5.5.35-log, Binlog ver: 4                                                              |
| mysql-bin.000005 | 107 | Query       |         1 |         175 | BEGIN                                                                                              |
| mysql-bin.000005 | 175 | Query       |         1 |         286 | use `mydb`; insert into tutor values(10,'huojianhua','M',32)                                       |
| mysql-bin.000005 | 286 | Xid         |         1 |         313 | COMMIT /* xid=60 */                                                                                |
| mysql-bin.000005 | 313 | Query       |         1 |         381 | BEGIN                                                                                              |
| mysql-bin.000005 | 381 | Query       |         1 |         493 | use `mydb`; insert into tutor values(11,'luozhixiang','M',35)                                      |
| mysql-bin.000005 | 493 | Xid         |         1 |         520 | COMMIT /* xid=69 */                                                                                |
| mysql-bin.000005 | 520 | Query       |         1 |         588 | BEGIN                                                                                              |
| mysql-bin.000005 | 588 | Query       |         1 |         681 | use `mydb`; delete from tutor where TID=10                                                         |
| mysql-bin.000005 | 681 | Xid         |         1 |         708 | COMMIT /* xid=71 */                                                                                |
| mysql-bin.000005 | 708 | Query       |         1 |         873 | use `mydb`; grant select on mydb.tutor to 'zhengyansheng'@'192.168.10.15' identified by 'password' |
+------------------+-----+-------------+-----------+-------------+----------------------------------------------------------------------------------------------------+
11 rows in set (0.00 sec)
  • 經過linux命令行查看二進制日誌事件記錄信息(能夠看到執行命令的時間)

[root@localhost ~]# mysqlbinlog --start-position=175 /mydata/data/mysql-bin.000005
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!40019 SET @@session.max_insert_delayed_threads=0*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#150306 16:51:46 server id 1  end_log_pos 107 	Start: binlog v 4, server v 5.5.35-log created 150306 16:51:46
# Warning: this binlog is either in use or was not closed properly.
BINLOG '
omr5VA8BAAAAZwAAAGsAAAABAAQANS41LjM1LWxvZwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAEzgNAAgAEgAEBAQEEgAAVAAEGggAAAAICAgCAA==
'/*!*/;
# at 175
#150306 16:55:01 server id 1  end_log_pos 286 	Query	thread_id=13	exec_time=0	error_code=0
use `mydb`/*!*/;
SET TIMESTAMP=1425632101/*!*/;
SET @@session.pseudo_thread_id=13/*!*/;
SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
SET @@session.sql_mode=0/*!*/;
SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
/*!\C utf8 *//*!*/;
SET @@session.character_set_client=33,@@session.collation_connection=33,@@session.collation_server=33/*!*/;
SET @@session.lc_time_names=0/*!*/;
SET @@session.collation_database=DEFAULT/*!*/;
insert into tutor values(10,'huojianhua','M',32)
/*!*/;
# at 286
#150306 16:55:01 server id 1  end_log_pos 313 	Xid = 60
COMMIT/*!*/;
# at 313
#150306 17:05:23 server id 1  end_log_pos 381 	Query	thread_id=15	exec_time=0	error_code=0
SET TIMESTAMP=1425632723/*!*/;
BEGIN
/*!*/;
# at 381
#150306 17:05:23 server id 1  end_log_pos 493 	Query	thread_id=15	exec_time=0	error_code=0
SET TIMESTAMP=1425632723/*!*/;
insert into tutor values(11,'luozhixiang','M',35)
/*!*/;
# at 493
#150306 17:05:23 server id 1  end_log_pos 520 	Xid = 69
COMMIT/*!*/;
# at 520
#150306 17:06:03 server id 1  end_log_pos 588 	Query	thread_id=15	exec_time=0	error_code=0
SET TIMESTAMP=1425632763/*!*/;
BEGIN
/*!*/;
# at 588
#150306 17:06:03 server id 1  end_log_pos 681 	Query	thread_id=15	exec_time=0	error_code=0
SET TIMESTAMP=1425632763/*!*/;
delete from tutor where TID=10
/*!*/;
# at 681
#150306 17:06:03 server id 1  end_log_pos 708 	Xid = 71
COMMIT/*!*/;
# at 708
#150306 17:07:25 server id 1  end_log_pos 873 	Query	thread_id=15	exec_time=0	error_code=0
SET TIMESTAMP=1425632845/*!*/;
grant select on mydb.tutor to 'zhengyansheng'@'192.168.10.15' identified by 'password'
/*!*/;
DELIMITER ;
# End of log file
ROLLBACK /* added by mysqlbinlog */;
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;
  • mysqlbinlog導出備份文件

[root@localhost ~]# mysqlbinlog --start-position=175 /mydata/data/mysql-bin.000005 > 05.sql
  • 導入數據庫

mysql> source /root/05.sql


  • 總述:開啓二進制日誌後,全部對數據庫進行的操做(引發數據庫改變或將要引發數據庫改變的)都會被記錄到二進制日誌文件當中,因此二進制日誌是在MySQL數據庫作及時點恢復的重要日誌文件,應該天天作備份,若是空間容許的狀況下,不建議刪除任何二進制日誌文件,能夠將其保存到備份目錄中,或許之後會用到。


備份策略:

星期天進行全備+天天進行二進制日誌增量備份

Bash腳本:

#!/bin/bash
#Author:Allentuns
#backup mysql database
#soft:mysqldump
#

User='root'
Datadir="/mydata/data"
Week=`date +%w`
Curtime=`date +%F`
Backupdir='/backup'

. /etc/profile

function full_backup_myisam()
{
    [ ! -d '$Backupdir/$Curtime' ] && mkdir -p $Backupdir/$Curtime
    cd $Backupdir/$Curtime

    #Start backup full mysql(engines:MyISAM)
        mysqldump -u$User -p$Password -h $Host --master-data=2 --flush-logs --lock-all-tables --events --all-databases |gzip > full_`date +%Y-%m-%d-%H-%M-%S`.sql.gz
        
    #Delete binary log
    binlog_rm=`tail -n 1 $Datadir/mysql-bin.index |sed 's@.\/@@'`
    mysql -u$User -p$Password -h $Host -e "purge binary logs to '$binlog_rm'"
}


function full_backup_innodb()
{
    [ ! -d '$Backupdir/$Curtime' ] && mkdir -p $Backupdir/$Curtime
    cd $Backupdir/$Curtime

    #Start backup full mysql(engines:InnoDB)
    mysqldump -u$User -p$Password -h $Host --master-data=2 --flush-logs --single-transaction --quick --events --all-databases |gzip > full_`date +%Y-%m-%d-%H-%M-%S`.sql.gz

    #Delete binary log
    binlog_rm=`tail -n 1 $Datadir/mysql-bin.index |sed 's@.\/@@'`
    mysql -u$User -p$Password -h $Host -e "purge binary logs to '$binlog_rm'"
}

function incre_backup()
{
    [ ! -d '$Backupdir/$Curtime' ] && mkdir -p $Backupdir/$Curtime
    cd $Backupdir/$Curtime

    #Start cp binary log
    mysqladmin -u$User -p$Password -h $Host flush-logs
    binlog_cp=`head -n -1 $Datadir/mysql-bin.index |sed 's@.\/@@'`
    for i in $binlog_cp
    do
        cp -p $Datadir/$i ./
    done

    #Delete binary log
    binlog_rm=`tail -n 1 $Datadir/mysql-bin.index |sed 's@.\/@@'`
    mysql -u$User -p$Password -h $Host -e "purge binary logs to '$binlog_rm'"
}

if [[ $Week -eq 0 ]];then
    full_backup_myisam
    #full_backup_innodb
else
    incre_backup
fi


mysqldump.sh分庫備份腳本

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

User='root'
Password='123456'
hostname=`hostname`
Backupdir='/data/backup'
email="13260071987@139.com"

inet=`/sbin/ip a |grep "BROADCAST" |wc -l`
if [ $inet -eq 2 ];then
    local_ip="$(/sbin/ifconfig eth1|grep 'inet addr'|awk -F : '{print $2}'|cut -d ' ' -f1)"
else
    local_ip="$(/sbin/ifconfig eth0|grep 'inet addr'|awk -F : '{print $2}'|cut -d ' ' -f1)"
fi

if [ ! -d "$Backupdir" ];then
    mkdir -p $Backupdir
fi

dbs=`mysql -u$User -p$Password -e 'show databases;'|sed 1d |egrep -v "information_schema|test|mysql"`
for db in $dbs
do
    mysqldump -u$User -p$Password --databases $db --lock-all-tables --events |gzip > $Backupdir/${db}_`date +%F`.sql.gz
done

if [ $? -ne 0 ];then  
    echo "Server_name:$(hostname) Server_ip:$local_ip $(date +"%y-%m-%d %H:%M:%S") mysql full backup Fail!"|/bin/mail -s "Database: [$dbs} Daily Full Backup Fail!" $email  
    exit 1  
fi 

find "$Backupdir" -name "*.sql.gz" -ctime +7 -type f -exec rm -rf {} \;


添加crond任務計劃

[root@localhost script]# crontab -e
30 23 * * * /usr/local/script/mysqldump_full_backup.sh
相關文章
相關標籤/搜索