如何實現MySQL數據庫使用情況的審計
如何實現MySQL數據庫使用情況的審計
最佳答案mysql的審計功能
mysql服務器自身沒有提供審計功能,但是我們可以使用init-connect + binlog的方法進行mysql的操作審計。由於mysql binlog記錄了所有對數據庫長生實際修改的sql語句,及其執行時間,和connection_id但是卻沒有記錄connection_id對應的詳細用戶信息。在後期審計進行行為追蹤時,根據binlog記錄的行為及對應的connection-id 結合 之前連接日誌記錄 進行分析,得出最後的結論。
1. 設置init-connect
1.1 創建用於存放連接日誌的數據庫和表
create database accesslog;
CREATE TABLE accesslog.accesslog (`id` int(11) primary key auto_increment, `time` timestamp, `localname` varchar(30), `matchname` varchar(30))
1.2 創建用戶權限
可用現成的root用戶用於信息的讀取
grant select on accesslog.* to root;
如果存在具有to *.* 權限的用戶需要進行限制。
這裏還需要註意用戶必須對accesslog表具有insert權限
grant select on accesslog.* to [email protected]
1.3 設置init-connect
在[mysqld]下添加以下設置:
init-connect=’insertinto accesslog.accesslog(id, time, localname, matchname)
values(connection_id(),now(),user(),current_user());’
------註意user()和current_user()的區別
log-bin=xxx
這裏必須開啟binlog
1.4 重啟數據庫生效
shell> /etc/init.d/mysql restart
2. 記錄追蹤
2.1 thread_id確認
可以用以下語句定位語句執行人
Tencent:~ # mysqlbinlog --start-datetime=‘2011-01-26 16:00:00‘
--stop-datetime=‘2011-01-26 17:00:00‘ /var/lib/mysql/mysql-bin.000010
| grep -B 5 ‘wsj‘
COMMIT/*!*/;
# at 767
#110126 16:16:43 server id 1 end_log_pos 872 Query thread_id=19 exec_time=0 error_code=0
use test/*!*/;
SET TIMESTAMP=1296029803/*!*/;
create table wsj(id int unsigned not null)
--
BEGIN
/*!*/;
# at 940
#110126 16:16:57 server id 1 end_log_pos 1033 Query thread_id=19 exec_time=0 error_code=0
SET TIMESTAMP=1296029817/*!*/;
insert into wsj(id) values (1)
--
BEGIN
/*!*/;
# at 1128
#110126 16:16:58 server id 1 end_log_pos 1221 Query thread_id=19 exec_time=0 error_code=0
SET TIMESTAMP=1296029818/*!*/;
insert into wsj(id) values (2)
2.2 用戶確認
thread_id 確認以後,找到元兇就只是一條sql語句的問題了。
mysql> select * from accesslog where id=19;
+----+---------------------+---------------------+-----------+
| id | time | localname | matchname |
+----+---------------------+---------------------+-----------+
| 19 | 2011-01-26 16:15:54 | [email protected]