linux下MySQL操做歷史記錄 ~/.mysql_history

mysql會給出咱們最近執行的SQL命令和腳本;同linux command保存在~/.bash_history同樣,你用mysql鏈接MySQL server的全部操做也會被記錄到~/.mysql_history文件中,這樣就會有很大的安全風險了,如添加MySQL用戶的sql也一樣會被明文記錄到此文件中。

1,查看你係統的~/.mysql_history隱藏文件

(個人測試環境下,通常linux的mysql用戶來管理,因此在/home/mysql目錄下會有這個文件)
-bash-3.2$ ls -al | grep mysql_
-rw------- 1 mysql mysql 5006 Apr 10 18:53 .mysql_history
 
 

2,測試MySQL用戶管理的SQL會被記錄

 
2.1 用linux用戶mysql, 使用mysql命令行工具登陸MySQL server. 添加用戶"his_user@localhost",並設置密碼
 
mysql> grant select on rep.* to his_user@localhost identified by '123';
Query OK, 0 rows affected (0.00 sec)
 
mysql>

2.2 斷開剛纔的mysql鏈接,查看/home/mysql/.mysql_history文件,可見剛纔添加mysql user的操做已被記錄,包括明文密碼123.
 
-bash-3.2$ tail -1 ~/.mysql_history
grant select on rep.* to his_user@localhost identified by '123';
 
注意說明:這個.mysql_history不是隻存在於MySQL所在的Server, 任何你可以遠程用mysql鏈接,都會在此server上的當前用戶的~目錄下建立這個隱藏文件。
 

3, 如何清除使用痕跡,若是在生產環境中,通常不會依賴此記錄來做審計,從上面演示能夠看出,還存在必定的風險。

 
2.1 徹底清除~/.mysql_history。
 
2.1.1 刪除如今的.mysql_history文件
-bash-3.2$ rm ~/.mysql_history
 
2.1.2 建立它的軟鏈接(緣由後面說明)
-bash-3.2$ ln -s /dev/null ~/.mysql_history
 
查看軟鏈接建立成功。
-bash-3.2$ ls -al | grep mysql_
lrwxrwxrwx 1 mysql mysql 9 Apr 10 20:30 .mysql_history -> /dev/null
測試是否生效:鏈接mysql, 操做,斷開鏈接,查看操做是否還被記錄。
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| backup |
-------------------------
mysql> exit
Bye
-bash-3.2$ cat ~/.mysql_history
 
可見,上面的show databases;操做命令沒有被記錄,同時當你斷開ssh後,從新鏈接mysql, 此時按「向上」鍵已無歷史操做記錄提示,說明生效了。
想要從新生效, 你直接刪除掉~/.mysql_history,當你下次再鏈接,退出後,就會從新建立此文件了。
 
2.2 只清除敏感信息;若是不想徹底禁用此功能,只是想每次作一些敏感操做後,把此文件清空即可以了。
 
-bash-3.2$ cat /dev/null > ~/.mysql_history
 
好比你修改了MySQL用戶信息,退mysql connection後,執行上操做,把所有操做痕跡清空了。
 
3 ~/.mysql_history文件的產生原理
 
3.1 由於mysql工具自己就是有一個shell, 每次mysql鏈接退出後,都會把這次操做的信息記錄到~/.mysql_history文件中,
若是此文件不存在,會先建立,再記錄(像上面的把它刪除後,或才安裝的MySQL)
 
3.2 此文件的名字,實際上是根據MYSQL_HISTFILE這個linux環境變量來設置了, 默認是這個~/.mysql_history值,那咱們測試一下其餘值。

3.2.1 在linux用戶的~/.bash_profile 中添加一行export MYSQL_HISTFILE=/home/mysql/.mydb_history
目錄根據你的linux用戶本身設置,個人測試用戶是mysql.
-bash-3.2$ vi ~/.bash_profile
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
PATH=$PATH:/usr/sbin
export MYSQL_HISTFILE=/home/mysql/.mydb_history
 
3.2.2 退出linux鏈接,從新登陸linux; 使用mysql來鏈接數據庫,操做,退出connection, 檢查~/.mydb_history隱藏文件是否建立,並檢查剛纔操做是否被記錄。
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
----------------------
//退出mysql
mysql> exit
Bye
//查看隱藏文件是否建立
-bash-3.2$ cd ~; ls -tal | grep mydb_history
-rw------- 1 mysql mysql 16 Apr 10 20:55 .mydb_history
// 查看「show databases"命令是否被正確記錄到文件中
-bash-3.2$ tail -1 ~/.mydb_history
show databases;
 
從上能夠說明:此文件的文件名來自於MYSQL_HISTFILE。

原文地址:http://www.cnblogs.com/milantgh/p/3602206.html?utm_source=tuicool&utm_medium=referral