init_connect + binlog 记录 mysql 操作日志
简介
mysql 的 init_connect 变量是每个客户端连上数据库服务器时执行的一组数据,这组数据可以是一个或者多个sql语句。
A string to be executed by the server for each client that connects. The string consists of one or more SQL statements, separated by semicolon characters.
mysql 的 binlog 日志用于记录所有更新了数据库内容的sql语句,以事件的形式保存。
The server's binary log consists of files containing “events” that describe modifications to database contents.
一、记录连接信息
创建表存放日志
CREATE DATABASE accesslog;
CREATE TABLE accesslog.accesslog (
`id` INT (11) PRIMARY KEY auto_increment,
`time` TIMESTAMP,
`localname` VARCHAR (30),
`matchname` VARCHAR (30)
)
设置用户权限
GRANT SELECT ON accesslog.* to root@localhost IDENTIFIED BY 'password'
设置init_connect
在 mysql 配置文件里(my.cnf或者my.ini)里[mysqld]里添加如下设置
init_connect='INSERT INTO accesslog.accesslog VALUES(connection_id(),now(),user(),current_user());'
然后重启数据库。
二、查询binlog
查询binlog是否打开
mysql> show variables like 'log_bin';
如果没有开启则开启binlog 打开mysql配置文件
vim /etc/my.cnf
在[mysqld] 区块添加如下设置
logb-bin=mysql-bin
mysql-bin是日志文件的前缀名 然后重启服务器生效
查看binlog日志位置
binlog 日志默认存储在数据目录,即 mysql 配置文件里的 datadir 目录。如果log-bin写了完整的目录,则日志文件在相应目录。 在目录下能看到如下文件就是啦

导出日志
mysql 自带的工具 mysqlbinlog 用于导出binlog日志,格式如下:
/mysql/bin/mysqlbinlog --database=test --start-date="2016-03-25 00:00:00" --stop-date="2016-03-28 15:00:00" /mysql/data/mysql-bin.000071 > test
--database
: 指定数据库名--start-date
: 开始时间--stop-date
: 结束时间
如果star-date 到 stop-date 跨越了好几个binlog文件可以通过mysql-bin.000*的方式模糊指定。
这样就导出了 2016-03-25 00:00:00 到 2016-03-28 15:00:00 之间执行的所有修改过数据的sql语句了。
格式如下

cat test.sql | grep ‘TABLE_NAME’ > xx.sql
审计与恢复
如上,通过查找binlog能找到客户端连接数据库的id,去查前面建立的accesslog表就可以找到是哪个用户操作的。 另外,当发生了误操作之后可以利用该方法恢复数据。 假如2016-3-25 13:10:00 发生了误操作。首先找到最近的一次数据库备份,假如是2016-03-01 00:00:00 那么则导出从2016-03-01 00:00:00到2016-3-25 13:10:00之间的binlog记录,然后删除其中的误操作语句(一定要删除)。接下来执行数据库备份,然后执行binlog导出的sql记录即可将数据库恢复至最新版本。
来源:oschina
链接:https://my.oschina.net/u/1243330/blog/648776