目前社區版本的mysql的審計功能還是比較弱的,基於插件的審計目前存在於Mysql的企業版、Percona和MariaDB上,但是mysql社區版本有提供init-connect選項,基於此我們可以用它來完成審計功能。
init-connect參數說明:
http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_init_connect
step1:創建用戶數據庫表
set names utf8 create database auditlog; create table auditlog.t_audit( id int not null auto_increment, thread_id int not null, login_time timestamp, localname varchar(50) default null, matchname varchar(50) default null, primary key (id) )ENGINE=InnoDB default charset=utf8 comment '審計用戶登錄信息';
step2:授權所有的用戶擁有對審計表的插入權限
select concat("grant insert on auditlog.t_audit to '",user,"'@'",host,"';") from mysql.user; #拼結授權語句
…… flush privileges;
注意,以后每添加一個用戶都必須授權此表的插入權限,要不會連接不上。
step3:設置init_connect參數
set global init_connect='insert into auditlog.t_audit(id,thread_id,login_time,localname,matchname) values(null,connection_id(),now(),user(),current_user());';
並在配置文件中增加如下語句:
init-connect='insert into auditlog.t_audit(id,thread_id,login_time,localname,matchname) values(null,connection_id(),now(),user(),current_user());'
以便下次重啟時能生效
驗證:
我們登陸后並刪除一條記錄,查看binlog,我們可以看到此操作的thread_id為7:

然后我們來查看此表t_audit表:
[zejin] 3301>select * from auditlog.t_audit; +----+-----------+---------------------+---------------------------+-------------------------+ | id | thread_id | login_time | localname | matchname | +----+-----------+---------------------+---------------------------+-------------------------+ | 1 | 5 | 2016-08-10 11:01:07 | user_app@192.168.1.240 | user_app@192.168.1.% | | 2 | 6 | 2016-08-10 11:02:02 | user_app@192.168.1.236 | user_app@192.168.1.% | | 3 | 7 | 2016-08-10 11:19:54 | user_yunwei@192.168.1.240 | user_yunwei@192.168.1.% | +----+-----------+---------------------+---------------------------+-------------------------+ 3 rows in set (0.00 sec)
可以看到thread_id為7的用戶為user_yunwei,在192.168.1.240機器上操作刪除的,完成了對數據的簡單審計。
擴展說明:
1.init-connect只會在連接時執行,不會對數據庫產生大的性能影響
2.init-connect是在連接時執行的動作命令,故可以用它來完成其它的功能,如:init_connect='SET autocommit=0'
3.init-connect不會記錄擁有super權限的用戶記錄,為了防止init_connect語句由於語法錯誤或權限問題而所有用戶都登陸不了的情況,保證至少super用戶能登陸並修改此值
