MySQL进行BINLOG回闪

MySQL数据恢复

前段时间因为要保证数据恢复的质量,写了一个进行回滚的脚本。

binglog2sql工具介绍

binglog2sql是一款用于解析binlog的工具,纯Python开发,安装需要有Python环境;

安装

git clone https://github.com/danfengcao/binlog2sql.git && cd binlog2sql

pip install -r requirements.txt

MySQL配置

[mysqld]

server_id = 1

log_bin = /var/log/mysql/mysql-bin.log

max_binlog_size = 1G

binlog_format = row

binlog_row_image = full

脚本内容

#!/bin/bash
user="root"
password="hao_123"
host="xxxx"
port="3306"


binglog=`mysql -u${user} -p${password} -h${host} -e "show master logs;"|grep -v ^Log`
echo -e "最新的的binglog:\n${binglog}"

cd /root/binlog2sql/binlog2sql
read -p "库名:" db
read -p "表名:" table
read -p "binglog文件:" bin
echo -e "格式:年-月-日 时:分:秒"
read -p "删除的大概时间:" time
read -p "结束的大概时间:" datatime
python ./binlog2sql.py -h${host} -u${user} -p${password} -P${port} -d ${db} -t ${table} --start-file="${bin}" --start-datetime="${time}" --stop-datetime="${datatime}" > /tmp/rollback.sql

echo -e "这个时间点执行的SQL是:"
cat /tmp/rollback.sql

read -p "开始位置:" sp
read -p "结束位置:" ep
read -p "输入Yes生成回滚文件:" yes
  if [[ "${yes}" == "yes" ]];then
     python ./binlog2sql.py -h${host} -u${user} -p${password} -P${port} -d ${db} -t ${table} --start-file="${bin}" --start-position="${sp}" --stop-position="${ep}" -B > /tmp/rollback.sql
fi

if [ $? -eq 0 ];then
   echo "rollback file success!"
fi

echo -e "回滚的SQL语句是:"
cat /tmp/rollback.sql
read -p "输入Yes开始回滚到数据库:" yes
  if [[ "${yes}" == "yes" ]];then
  mysql -u${user} -p${password} -h${host} < /tmp/rollback.sql
  fi
if [ $? -eq 0 ];then
  echo "rollback MySQL success!"
fi

这时候对于一些误操作,可以通过过滤大概的时间,和指定的SQL语句进行回闪,保证了数据的安全性。

相关推荐