创建用户而不删除,更新和更改MySQL中的权限

时间:2013-10-01 18:09:24

标签: mysql privileges audit auditing

我必须为某些用户提供对我的数据库的直接访问以进行审计,并且应该添加限制以避免这些新用户没有删除,更新和更改权限。

1 个答案:

答案 0 :(得分:1)

只需创建一个用户并授予 SELECT权限。

CREATE USER user_name@host_name identified by 'password';
GRANT SELECT ON db_name.* TO user_name@host_name;

检查用户使用的权限

SHOW GRANTS FOR user_name@host_name;

并确保用户只有GRANT USAGEGRANT SELECT ON db_name.*


假设我的my_db数据库中包含test表,我想创建一个名为user1的用户,只允许从本地主机连接,并且能够从该数据库中的所有表中读取数据,但无法插入,更改和删除数据。

mysql> create user user1@localhost identified by 'password';
Query OK, 0 rows affected (0.00 sec)

mysql> show grants for user1@localhost;
+--------------------------------------------------------------------------------------------------------------+
| Grants for user1@localhost                                                                                   |
+--------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'user1'@'localhost' IDENTIFIED BY PASSWORD '*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19' |
+--------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> grant select on my_db.* to user1@localhost;
Query OK, 0 rows affected (0.00 sec)

mysql> show grants for user1@localhost;
+--------------------------------------------------------------------------------------------------------------+
| Grants for user1@localhost                                                                                   |
+--------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'user1'@'localhost' IDENTIFIED BY PASSWORD '*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19' |
| GRANT SELECT ON `my_db`.* TO 'user1'@'localhost'                                                             |
+--------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

现在让我们看看user1能做什么不能做什么

$ mysql -uuser1 -p 
mysql> use mysql
ERROR 1044 (42000): Access denied for user 'user1'@'localhost' to database 'mysql'
mysql> use test
ERROR 1044 (42000): Access denied for user 'user1'@'localhost' to database 'test'
mysql> use my_db
Database changed

如您所见,我们的user1只能连接到my_db数据库。

现在让我们看看用户可以对表测试中的数据做什么(该数据库中唯一的表)

mysql> select * from test;
+------+
| id   |
+------+
|    1 |
|    2 |
+------+
2 rows in set (0.00 sec)

mysql> insert into test values (3);
ERROR 1142 (42000): INSERT command denied to user 'user1'@'localhost' for table 'test'
mysql> delete from test where id = 1;
ERROR 1142 (42000): DELETE command denied to user 'user1'@'localhost' for table 'test'
mysql> update test set id = 10 where id = 1;
ERROR 1142 (42000): UPDATE command denied to user 'user1'@'localhost' for table 'test'

同样,用户只能从表格中选择。