目前社區版本的mysql的審計功能仍是比較弱的,基於插件的審計目前存在於Mysql的企業版、Percona和MariaDB上,可是mysql社區版本有提供init-connect選項,基於此咱們能夠用它來完成審計功能。html
init-connect參數說明:mysql
http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_init_connectsql
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:受權全部的用戶擁有對審計表的插入權限app
select concat("grant insert on auditlog.t_audit to '",user,"'@'",host,"';") from mysql.user; #拼結受權語句
…… flush privileges;
注意,之後每添加一個用戶都必須受權此表的插入權限,要不會鏈接不上。性能
step3:設置init_connect參數spa
set global init_connect='insert into auditlog.t_audit(id,thread_id,login_time,localname,matchname) values(null,connection_id(),now(),user(),current_user());';
驗證:插件
[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)