用户及授权
授权
创建用户并授权
GRANT 权限列表 ON 库名.表名 TO '用户名'@'客户端地址' IDENTIFIED BY '密码' WITH GRANT OPTION;
- 权限列表:用户的操作权限,如
SELECT,INSERT,UPDATE等,如果要授予所的权限则使用ALL
- 表名:表名,如果要授予该用户对所有数据库和表的相应操作权限则可用
*表示,如*.*
- WITH GRANT OPTION:用户拥有授权权限
- 示例:
# 授予zzg用户在本地登陆的权限
mysql> grant select,update(phone_number,email) on nsd2021.employees to zzg@'localhost' identified by 'NSD2021@tedu.cn';
# 授予zzg用户在任意地址登陆的权限
GRANT SELECT, INSERT, UPDATE(phone_number,email) ON nsd2021.employees to zzg@'%' IDENTIFIED BY 'NSD2021@tedu.cn';
客户端连接测试
# 安装mysql/mariadb客户端
[root@zzgrhel8 ~]# yum install -y mariadb
[root@zzgrhel8 ~]# mysql -h服务器 -u用户名 -p密码
相关查询指令
SELECT USER();
SHOW GRANTS;
SHOW GRANTS FOR 用户名@'客户端地址';
SET password=password('密码');
SET PASSWORD FOR 用户名@'客户端地址'=password('密码');
DROP USER 用户名@'客户端地址';
授权库mysql
相关表
- user:记录已有的授权用户及权限
- db:记录已有授权用户对数据库的访问权限
tables_priv:记录已有授权用户对表的访问权限
columns_priv:记录已有授权用户对字段的访问权限
mysql> grant select,insert,update(phone_number,email) on nsd2021.employees to zzg@'localhost' identified by 'NSD2021@tedu.cn';
mysql> select * from tables_priv where User like '%zzg%'\G
*************************** 1. row ***************************
Host: localhost
Db: nsd2021
User: zzg
Table_name: employees
Grantor: root@localhost
Timestamp: 0000-00-00 00:00:00
Table_priv: Select,Insert
Column_priv: Update
1 row in set (0.00 sec)
撤销权限
REVOKE 权限列表 ON 库名.表名 FROM 用户名@'客户端地址';
# 查看用户有哪些权限
SELECT host, user FROM mysql.user;
# 查看权限
SHOW GRANTS FOR 用户名@'客户端地址';
# 撤回授权权限
REVOKE GRANT OPTION ON *.* FROM 用户名@'客户端地址';
# 撤回用户删除权限
REVOKE DELETE ON *.* FROM 用户名@'客户端地址';
# 创建tom用户,具有授权权限
mysql> grant all on *.* to tom@'%' identified by 'NSD2021@tedu.cn' with grant option;
# tom登陆后,创建jerry用户
[root@zzgrhel8 ~]# mysql -utom -pNSD2021@tedu.cn -h192.168.1.11
MySQL [(none)]> grant select on nsd2021.* to 'jerry'@'%' identified by 'NSD2021@tedu.cn';
root密码恢复
步骤
- 停止MySQL服务
- 跳过授权表启动MySQL服务程序
- 修改root密码
- 以正常方式重启MySQL服务程序
示例:
# 停止MySQL服务
[root@node10 ~]# systemctl stop mysqld
# 修改配置文件,跳过授权表启动MySQL服务程序
[root@node10 ~]# vim /etc/my.cnf
[mysqld]
skip-grant-tables
... ...
# 启动服务
[root@node10 ~]# systemctl start mysqld
# 修改root密码
[root@node10 ~]# mysql
mysql> update mysql.user set authentication_string=password('123456')
-> where user='root' and host='localhost';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 1
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
# 以正常方式重启MySQL服务程序
[root@node10 ~]# systemctl stop mysqld
[root@node10 ~]# vim /etc/my.cnf
[mysqld]
# skip-grant-tables
... ...
[root@node10 ~]# systemctl start mysqld
[root@node10 ~]# mysql -uroot -p123456