mysql创建远程用户并授权

时间:2022-09-08 14:44:15

1、连上Mysql,如果Mysql不在本地,则可以用SSH连上

bash-4.2$ mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.6.37 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

因为我这里是刚安装的,还没创建密码,所以可以直接进来
否则可以用:

# mysql -u [user] -p

2、查询当前的用户,用户可登录的IP,还有用户的密码

mysql> select Host,User,Password from mysql.user;
+-------------------------+------+----------+

| Host | User | Password |
+-------------------------+------+----------+

| localhost | root | |
| iz2ze6u0apce8jpapxeubpz | root | |
| 127.0.0.1 | root | |
| ::1 | root | |
| localhost | | |
| iz2ze6u0apce8jpapxeubpz | | |
+-------------------------+------+----------+

6 rows in set (0.00 sec)

mysql>

一共有5个mysql账号,Host列可以看出来,这些账号都只支持服务器本机连接,现在我们来创建一个远程用户;

mysql> create user aowei identified by 'aowei';
Query OK, 0 rows affected (0.00 sec)

mysql>

mysql> select Host,User,Password from mysql.user;
+-------------------------+-------+-------------------------------------------+

| Host | User | Password |
+-------------------------+-------+-------------------------------------------+

| localhost | root | |
| iz2ze6u0apce8jpapxeubpz | root | |
| 127.0.0.1 | root | |
| ::1 | root | |
| localhost | | |
| iz2ze6u0apce8jpapxeubpz | | |
| % | aowei | *52C1166B568F83580DEA51313AB855A9A26B6DAA |
+-------------------------+-------+-------------------------------------------+

7 rows in set (0.00 sec)

mysql>

这里我们看到,aowei这个账户是有密码了的;创建完成了,在程序里面连接发现还是没有权限,刚才我们只是创建了用户,还没有对这个用户分配权限

mysql> grant all privileges on *.* to 'aowei'@'%'identified by 'aowei' with grant option;           
Query OK, 0 rows affected (0.00 sec)

mysql>

all代表接受所有操作,比如 select,insert,delete….; . 代表所有库下面的所有表;% 代表这个用户允许从任何地方登录;为了安全期间,这个%可以替换为你允许的ip地址;

然后刷新mysql用户权限相关表


mysql> flush privileges ;
Query OK, 0 rows affected (0.00 sec)

mysql>

这时候我们看到已经可以远程连接了:
mysql创建远程用户并授权

如果还是连接不上,就看看这个
打开 mysql配置文件,是默认的3306,接着往下面看,有一个关键地方;

bind-address           = 127.0.0.1

这里mysql默认绑定了本地ip,不接受其他来源;注释掉,重启mysql 一切OK;