MySQL 设置 IP 白名单

发布时间 2023-08-11 23:28:35作者: Higurashi-kagome

1. 登录 MySQL

mysql -u root -p

2. 新增用户并授予权限

MySQL8 之前:

grant all on *.* to 'username'@'ip' identified by 'password' with grant option;

MySQL8 开始:

create user 'username'@'ip' identified with mysql_native_password by 'password';
grant all privileges on *.* to 'username'@'ip';

从 MySQL8 开始无法给未创建的用户授权。MySQL8 之前如果用户不存在会创建用户。

grant all表示授权所有操作,*.*表示授权所有数据库的所有表。

如果是赋予部分权限,可以如下:

grant select,create,drop,update,alter on *.* to 'username'@'ip' identified by 'password' with grant option;

3. 删除白名单用户的权限

DELETE FROM user WHERE User='username' and Host='ip';

这步慎做,删错了就登不上 MySQL 了。

Host 值为%或空表示所有 IP 都可登录,一般来说此类行需要删掉。

4. 刷新权限

FLUSH PRIVILEGES;

5. 测试

mysql -h ip -u root -p

参考:MySQL 配置白名单MySQL8 关于授权遇到的问题MySQL 设置白名单教程