您的位置:首页 > 运维架构 > Linux

linux下MySQL操作历史记录 ~/.mysql_history

2015-11-25 18:27 555 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: