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