今天分享一下binlog2sql,它是一款比较常用的数据恢复工具,可以通过它从MySQL binlog解析出你要的SQL,并根据不同选项,可以得到原始SQL、回滚SQL、去除主键的INSERT SQL等。主要用途如下:
该项目分享与git上,可以直接从git上获取,因此可以先安装git。
yum install -y pip
因binlog2sql依赖于python2.7或python3.4+版本,如果本机python版本较低,则无法使用。安装或升级python的方法可以参考 《python安装及升级》
如果系统中没有安装pip,则需要先安装pip,因为后续需要用pip安装python所需的包。
binlog2sql可以部署在其他机器上,而不是必须部署在mysql服务端上。
git clone https://Github.com/danfengcao/binlog2sql.git && cd binlog2sql
pip install -r requirements.txt
MySQL server必须设置以下参数。
[mysqld]
server_id = 128
log_bin = /data/mysql/mysql3306/logs/mysql-bin
max_binlog_size = 512M
binlog_format = row
binlog_row_image = full # 默认值,可以不显式设置
因binlog2sql是通过模拟从库的方式获取binlog,所以,数据库账号权限至少需设置为从库所需的权限。
-- 创建用户
mysql> create user data_rec@'192.168.56.%' identified by 'xxxxxxxx';
Query OK, 0 rows affected (0.01 sec)
-- 授权
mysql> GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO data_rec@'192.168.56.%';
Query OK, 0 rows affected (0.00 sec)
权限说明:
mysql> use testdb;
Database changed
mysql> create table t_test1 (id int primary key auto_increment ,c_name varchar(20), c_num int );
Query OK, 0 rows affected (0.02 sec)
mysql> insert into t_test1(c_name,c_num) values('aaaa',10),('abcc',15),('bacess',9),('andd',10);
Query OK, 4 rows affected (0.03 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> insert into t_test1(c_name,c_num) values('bbbaa',1),('dc',5),('vgcess',29),('hdgd',0);
Query OK, 4 rows affected (0.01 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2020-09-18 16:29:08 |
+---------------------+
1 row in set (0.00 sec)
mysql> delete from t_test1;
Query OK, 8 rows affected (0.00 sec)
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2020-09-18 16:29:26 |
+---------------------+
1 row in set (0.00 sec)
因知道大概误删除的时间,因此通过解析对应时间的binlog恢复出指定库表的数据,生成的结果是用于恢复的sql.
python binlog2sql.py --flashback -h 192.168.56.128 -udata_rec -p'xxxxxxxx' -d testdb -t t_test1 --start-file='mysql-bin.000003' --start-datetime='2020-09-18 16:29:08' --stop-datetime='2020-09-18 16:30:00' >/tmp/rec.sql
结果内容如下:
mysql> select * from t_test1;
Empty set (0.00 sec)
mysql> source /tmp/rec.sql;
Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.01 sec)
Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.00 sec)
mysql> select * from t_test1;
+----+--------+-------+
| id | c_name | c_num |
+----+--------+-------+
| 1 | aaaa | 10 |
| 2 | abcc | 15 |
| 3 | bacess | 9 |
| 4 | andd | 10 |
| 5 | bbbaa | 1 |
| 6 | dc | 5 |
| 7 | vgcess | 29 |
| 8 | hdgd | 0 |
+----+--------+-------+
8 rows in set (0.00 sec)
数据已恢复。
参考原文链接:https://github.com/danfengcao/binlog2sql。