MySQL中权限管理

时间:2022-09-22 08:27:35

一、访问控制

数据库服务器通常包含有重要的数据,这些数据的安全和完整可通过访问控制来维护。访问控制实际上就是为用户提供且仅提供他们所需的访问权。
mysql的用户账号及相关信息存储在名为mysql的数据库(系统)中,其中的user表包含了所有用户的账号,user表中的user列存储用户的登录 名。可以使用下面的sql语句查看数据库的使用者账号:

select user from mysql.user;
  • 1

MySQL中权限管理

创建用户账号

成功安装了mysql服务器后,系统会创建一个名为root的用户,root用户拥有对整个mysql服务器完全控制的权限。为了避免恶意用户冒名使用root账号操控数据库,通常需要创建一系列具备适当权限的账号,而尽可能地不用或少用root账号登录系统,以此来确保数据的安全访问。
创建用户名为zhangsan的新用户,口令为明文123:

create user'zhangsan'@'localhost'identified by'123';

MySQL中权限管理
如果想对明文123进行加密可以使用password()函数,它加密后返回的是散列值:

select password(123);

MySQL中权限管理

则此时的创建新用户的语句就为:

create user 'zhangsan'@'localhost'identified by password'上面通过password()函数加密的散列值';

删除用户

注意必须明确给出该账号的主机名

drop user zhangsan@localhost;

修改用户账号

rename user'zhangsan'@'localhost'to'lisi'@'localhost';

修改用户口令(密码)

新口令必须传递到password()中进行加密,或者是已经加密过的口令值(此时要加上引号)。
将用户zhangsan的口令修改成明文“hello”对应的散列值:

set password for 'zhangsan'@'localhost'=password('hello');

二、账户权限管理

新创建的用户账号没有访问权限,只有登录到mysql服务器,不能执行任何数据库操作,我们可以用下面的sql语句查看新创建的用户zhangsan的权限:

show grants for 'zhangsan'@'localhost';

MySQL中权限管理
根据输出结果,可以看到用户zhangsan仅有一个权限usage on 星号.星号,表示该用户对任何数据库和任何表都没有权限。
所以需要为该用户分配适当的访问权限。

权限的授予

权限的授予通过grant语句实现。下面是一些实例:

grant select(cust_id,cust_name) on mysql_test.customers to'zhangsan'@'localhost';--授予在数据库mysql_test的表customers上拥有对列cust_id和列cust_name的select权限
grant select ,update on mysql_test.customers to 'liming'@'localhost'identified by'123';--新建一个用户为liming,并授予其在数据库mysql_test的表customers上拥有select和update的权限
grant all on mysql_test.* to'zhangsan'@'localhost';--授予可以在数据库mysql_test中执行所有操作的权限
grant create user on *.* to'zhangsan'@'localhost';--授予系统中已存在用户zhangsan拥有创建用户的权限

权限的转移与限制

授予当前系统中一个不存在的用户zhou在数据库mysql_test的表customers上拥有select 和update 的权限,并允许其将自身的这个权限授予其他用户(通过with grant option):

grant select,update on mysql_test.customers to'zhou'@'localhost'identified by'123' with grant option;

如果上面with子句后面跟的是max_queries_per_hour count、
max_updates_per_hour count、
max_connections_per_hour count、
max_user_connections count
中的某一项,则该grant语句可用于限制权限

grant delete on mysql_test.customers to 'zhangsan'@'localhost' with max_queries_per_hour 1;--每小时只能处理一条delete语句的权限

权限的撤销

使用revoke可以实现权限的撤销,而不会删除用户

revoke select on mysql_test.customers from'zhangsan'@'localhost';--回收用户zhangsan在数据库mysql_test的表customers上的select权限

例子:

现在需要创建一个用户,该用户不能删除拥有 drop   delete权限,操作如下:

MySQL中权限管理

MySQL中权限管理

MySQL中权限管理

MySQL中权限管理

MySQL中权限管理

MySQL中权限管理