1、查看所有用户
use mysql;
select user,host from user;
2、创建用户
语法:
create user 用户名[@主机名] [identified by ‘密码’];
说明:
1.主机名默认值为%,表示这个用户可以从任何主机连接mysql服务器
2.密码可以省略,表示无密码登录
示例1:不指定主机名
use mysql;
select user,host from user;
create user test1;
select user,host from user;
exit;
其他示例:
create user 'test2'@'localhost' identified by '123';
说明:test2的主机为localhost表示本机,此用户只能登录本机的mysql.
create user 'test3'@% identified by '123';
说明:test3可以从任何机器连接到mysql服务器
create user 'test4'@'192.168.11.%' identified by '123';
说明:test2可以从192.168.11段的机器连接mysql
3、修改密码
方式1:通过管理员修改密码
set password for '用户名'@'主机'=password('密码');
方式2:create user 用户名[@主机名][identified by ‘密码’];
set password = password('密码');
方式3:通过修改mysql.user表修改密码
use mysql;
update user set authentication_string = password('321') where user='test1' and host='%';
flush privileges;
注意:
通过表的方式修改之后,需要执行flush pricileges;才能对用户生效。
5.7中user表中的authentication_string字段表⽰密码,⽼的⼀些版本中密码字段是
password。
4、给用户授权
创建用户之后,需要给用户授权,才有意义。
语法:
grant privileges on database.table to 'username'[@'host'][with grant option]
grant命令说明:
- priveleges (权限列表),可以是all,表⽰所有权限,也可以是select、update等权限,多个权限之间⽤逗号分开。
- ON ⽤来指定权限针对哪些库和表,格式为数据库.表名 ,点号前⾯⽤来指定数据库名,点号后⾯⽤来指定表名,. 表⽰所有数据库所有表。
- TO 表⽰将权限赋予某个⽤户, 格式为username@host,@前⾯为⽤户名,@后⾯接限制的主机,可以是IP、IP段、域名以及%,%表⽰任何地⽅。
- WITH GRANT OPTION 这个选项表⽰该⽤户可以将⾃⼰拥有的权限授权给别⼈。注意:经常有⼈在创建操作⽤户的时候不指定WITH GRANT OPTION选项导致后来该⽤户不能使⽤GRANT命令创建⽤户或者给其它⽤户授权。 备注:可以使⽤GRANT重复给⽤户添加权限,权限叠加,⽐如你先给⽤户添加⼀个select权限,然后又给⽤户添加⼀个insert权限,那么该⽤户就同时拥有了select和insert权限。
示例:
grant all on *.* to 'test1'@'%';
说明:给test1授权可以操作所有库所有权限,相当于dba
grant select on seata.* to 'test1'@'%';
说明:test1可以对seata库中所有的表执行select
grant select,update on seata.* to 'test1'@'%';
说明:test1可以对seata库中所有的表执行select、update
grant select(user,host) on mysql.user to 'test1'@'localhost';
说明:test1用户只能查询mysql.user表的user,host字段。
5、查看用户权限
语法:
show grants for '用户名'[@'主机']
show grants for 'test1'@'localhost';
show grants;
查看当前用户的权限,如:
show grants;
6、撤销用户权限
语法:
revoke privileges on database.table from '用户名'[@'主机'];
可以先通过show grants命令查询一下用户对于的权限,然后使用revoke命令撤销用户对应的权限,示例:
show grants for 'test1'@'localhost';
revoke select(host) on mysql.user from test1@localhost;
show grants for 'test1'@'localhost';
上⾯我们先通过grants命令查看test1的权限,然后调⽤revoke命令撤销对mysql.user表host字段的查询权限,最后又通过grants命令查看了test1的权限,和预期结果⼀致。
7、删除用户
方式1:
语法:
drop user '用户名'[@'主机']
示例:
drop user test1@localhost;
drop的⽅式删除⽤户之后,⽤户下次登录就会起效
方式2:
通过删除mysql.user表数据的方式删除,如下:
delete from user where user='用户名' and host='主机';
flush privileges;
注意通过表的方式删除的,需要调用flush privileges;刷新权限信息(权限启动的时候在内存中保存着,通过表的方式修改之后需要刷新一下)。
8、授权原则说明
- 只授予能满足需要的最小权限,防止用户干坏事,比如用户只能是需要查询,那就只给select权限就可以了,不要给用户赋予update、insert或者delete权限。
- 创建用户的时候限制用户的登录主机,一般是限制成制定IP或者内网IP段。
- 初始化数据库的时候删除没有密码的用户,安装完数据库的时候会自动创建一下用户,这些用户默认没有密码。
- 为每个用户设置满足密码复杂度的密码。
- 定期清理不需要的用户,回收权限或者删除用户。