1、作用

登录数据库
管理数据库对象

2、示例

  1. #格式
  2. '用户'@'白名单'
  3. #本地用户
  4. 'user'@'localhost'
  5. #单一IP
  6. 'user'@'192.168.10.240'
  7. #范围IP
  8. 'user'@'192.168.10.2%'
  9. 'user'@'192.168.10.%'
  10. 'user'@'192.168.10.240/255.255.255.0'
  11. 'user'@'%'
  12. #%等同于于*,表示所有

用户安全规范

  1. 1. 白名单尽量小,最好细化到单一IP,尽量不要使用%
  2. 2. 用户名要有特点
  3. 3. 无用的用户删除或者锁定
  4. 4. 密码复杂度
  5. #不常用
  6. 'user'@'%'
  7. 'user'@'db02'
  8. 'user'@'mingdikeji.com'

3、用户管理

3.1、查询用户

  1. #查询用户,白名单,密码,插件
  2. select User,Host,authentication_string,plugin from mysql.user;
  3. #查询user表定义
  4. desc mysql.user;

3.2、创建用户

  1. create user 'laidenglin'@'192.168.10.240' identified by '123456';
  2. flush privileges;
  3. #指定密码插件为:mysql_native_password
  4. create user 'laidenglin'@'192.168.10.240' identified with mysql_native_password by '123456';
  5. flush privileges;

MySQL 8.0 版本用户彩蛋

  1. 1. 必须先创建用户,再授权,不再支持grant创建用户和修改密码功能
  2. 不再支持: grant all on *.* to 'zabbix'@'%' identified by '123456';
  3. 2. 密码插件
  4. 8.0之前: mysql_native_password
  5. 8.0开始: caching_sha2_password
  6. #caching_sha2_password 导致的问题
  7. 老版本的客户端程序,连接不了8.0版本
  8. 例如: 客户端软件、主从、MHA
  9. #解决方法
  10. (1). 建用户时,指定mysql_native_password插件进行密码加密
  11. create user 'laidenglin'@'192.168.10.240' identified with mysql_native_password by '123456';
  12. (2). 修改用户密码插件
  13. alter user 'laidenglin'@'192.168.10.240' identified with mysql_native_password;
  14. (3). 配置文件中指定默认加密插件为mysql_native_password
  15. [mysqld]
  16. default_authentication_plugin=mysql_native_password

3.3、修改用户

  1. #修改密码
  2. alter user 'laidenglin'@'192.168.10.240' identified by '456789';
  3. flush privileges;
  4. #5.6版本修改密码
  5. update mysql.user set password=password("123") where user="root";
  6. flush privileges;
  7. #修改插件
  8. alter user 'laidenglin'@'192.168.10.240' identified with mysql_native_password;
  9. flush privileges;
  10. #修改密码和插件
  11. alter user 'laidenglin'@'192.168.10.240' identified with mysql_native_password by '654321';
  12. flush privileges;
  13. #修改白名单
  14. update mysql.user set host='127.0.0.1' where user='laidenglin' and host='192.168.10.240';
  15. flush privileges;

3.4、锁定用户

  1. #锁定用户
  2. alter user 'laidenglin'@'192.168.10.240' account lock;
  3. flush privileges;
  4. #锁定用户登录提示 (错误码: 3118)
  5. ERROR 3118 (HY000): Access denied for user 'laidenglin'@'localhost'. Account is locked.
  6. #解锁锁定用户
  7. alter user 'laidenglin'@'192.168.10.240' account unlock;
  8. flush privileges;
  9. #查看锁定用户
  10. select user,host,account_locked from mysql.user where account_locked = 'Y';

3.5、密码过期

不常用

  1. alter user 'laidenglin'@'192.168.10.240' password expire;
  2. flush privileges;
  3. #可以使用旧密码连接,不能运行命令,提示修改密码 (错误码: 1082)
  4. ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

3.6、删除用户

生产环境中,先备份mysql库,或备份mysql.user表,再执行删除用户

  1. drop user 'laidenglin'@'192.168.10.240';
  2. flush privileges;