利用mysql的audit審計(jì)功能記錄用戶操作信息
mysql數(shù)據(jù)庫中我們?nèi)绻胗涗浻脩舻牟僮餍畔?,可以通過audit審計(jì)功能來來實(shí)現(xiàn)。該功能是被自動(dòng)觸發(fā)的,在文件plugin_audit.h中可以看到比較詳細(xì)的定義。在audit插件中,可控制的變量包括THD以及事件。
其中事件分為兩種結(jié)構(gòu)體,可以進(jìn)行強(qiáng)制轉(zhuǎn)換:
***種:
- struct mysql_event_general
- {
- unsigned int event_subclass;
- int general_error_code;
- unsigned long general_thread_id;
- const char *general_user;
- unsigned int general_user_length;
- const char *general_command;
- unsigned int general_command_length;
- const char *general_query;
- unsigned int general_query_length;
- struct charset_info_st *general_charset;
- unsigned long long general_time;
- unsigned long long general_rows;
- };
觸發(fā)條件:
#define MYSQL_AUDIT_GENERAL_LOG 0 :在提交給general query log之前被觸發(fā)。
#define MYSQL_AUDIT_GENERAL_ERROR 1 :在發(fā)送給用戶錯(cuò)誤之前觸發(fā)。
#define MYSQL_AUDIT_GENERAL_RESULT 2 : 當(dāng)將結(jié)果集合發(fā)送給用戶后觸發(fā)。
#define MYSQL_AUDIT_GENERAL_STATUS 3 : 當(dāng)發(fā)送一個(gè)結(jié)果集或發(fā)生錯(cuò)誤時(shí)被觸發(fā)。
第二種:
- struct mysql_event_connection
- {
- unsigned int event_subclass;
- int status;
- unsigned long thread_id;
- const char *user;
- unsigned int user_length;
- const char *priv_user;
- unsigned int priv_user_length;
- const char *external_user;
- unsigned int external_user_length;
- const char *proxy_user;
- unsigned int proxy_user_length;
- const char *host;
- unsigned int host_length;
- const char *ip;
- unsigned int ip_length;
- const char *database;
- unsigned int database_length;
- };
觸發(fā)條件:
#define MYSQL_AUDIT_CONNECTION_CONNECT 0 : 完成認(rèn)證后觸發(fā)。
#define MYSQL_AUDIT_CONNECTION_DISCONNECT 1 : 連接被中斷時(shí)觸發(fā)。
#define MYSQL_AUDIT_CONNECTION_CHANGE_USER 2 : 在執(zhí)行COM_CHANGE_USER命令后觸發(fā)。
從上面的分析,我們可以看出,在event中存儲(chǔ)了相當(dāng)豐富的信息,將notify函數(shù)進(jìn)行了如下簡(jiǎn)單的修改:
- static void audit_null_notify(MYSQL_THD thd __attribute__((unused)),
- unsigned int event_class,
- const void *event)
- {
- const struct mysql_event_general *pEvent;
- if (log_fp == NULL)
- log_fp = fopen("/tmp/rec.log", "a");
- number_of_calls++;
- if (event_class == MYSQL_AUDIT_GENERAL_CLASS && log_fp != NULL){
- pEvent = (const struct mysql_event_general *) event;
- if ( pEvent->event_subclass == MYSQL_AUDIT_GENERAL_RESULT &&
- pEvent->general_query != NULL
- && *(pEvent->general_query) != '\0') {
- // fprintf(log_fp, "user:%s,host:%s,command:%s\n",&thd->security_ctx->priv_user[0],
- // (char *) thd->security_ctx->host_or_ip ,
- // pEvent->general_query);
- time_t cur = time(NULL);
- fprintf(log_fp, "%s %s\n%s\n", ctime(&cur) , pEvent->general_user , pEvent->general_query);
- fflush(log_fp);
- }
- }
- }
這樣,我們實(shí)現(xiàn)了記錄用戶名、用戶主機(jī)信息以及sql操作等相關(guān)信息。
【編輯推薦】
- mysql數(shù)據(jù)庫對(duì)binlog日志的處理
- MySQL索引背后的之使用策略及優(yōu)化
- Linux平臺(tái)mysql的安裝配置之常用操作
- NaviCat通過Http方式連接服務(wù)器的MySQL數(shù)據(jù)庫
- 詳解Discuz_WIN7_Apache_MySQL_PHP平臺(tái)搭建