MySQL 无法远程连接?

MySQL 无法远程连接?

先看清楚报错信息,一般都有解答。虽然报错信息写的有点难懂

0. 云服务器商防火墙 与 服务器防火墙

请登陆你的云服务器防火墙管理web进行相关配置。

服务器本身的防火墙配置可以使用:

sudo ufw status

STFW !

1. mysql deamon配置问题

/etc/mysql/mysql.conf.d/mysqld.cnf中,的

bind-address = 0.0.0.0 // 而不是127.0.0.1

然后

sudo systemctl restart mysql

2. mysql 认证方式

mysql_native_password : mysql vs. mysql2

报错信息如下 或类似:

  code: 'ER_NOT_SUPPORTED_AUTH_MODE',
  errno: 1251,
  sqlMessage: 'Client does not support authentication protocol requested by server; consider upgrading MySQL client',
  sqlState: '08004',
  fatal: true

javascript举例:应该安装mysql2, 用更新的认证方式

npm install mysql2

在你的javescript代码中使用

const mysql = require('mysql2');

3. 用户帐号相关问题

先查看所有用户的用户名可访问host (%表示什么ip都可以,通配符)

SELECT User, Host FROM mysql.user;

只有当

  • 用户名存在

  • 密码匹配

  • host可访问

  • 用户权限足够

    SHOW GRANTS FOR 'User'@'Host'; -- 查看用户权限
    

以上几点均满足时才行。

如何修改用户 User or Host or Password?

!!!不要直接修改mysql.user !!!

To modify the User, Host, or authentication information (password hash) in the mysql.user table, you can use the appropriate SQL commands. Below are the steps for safely making changes:


1. Modify the User Name

To rename a user, use the RENAME USER command. Do not directly update the mysql.user table.

RENAME USER 'old_user'@'old_host' TO 'new_user'@'old_host';

2. Modify the Host

To change the host for a user, use the RENAME USER command as well:

RENAME USER 'user_name'@'old_host' TO 'user_name'@'new_host';

3. Modify the Authentication Code (Password)

To update a user’s password, use the ALTER USER command:

ALTER USER 'user_name'@'host' IDENTIFIED BY 'new_password';

This command will automatically hash the password and update the authentication_string column in mysql.user.


4. Flush Privileges

After any manual modifications to mysql.user, run the following to apply the changes:

FLUSH PRIVILEGES;

5. Verify Changes

Verify that the changes were applied correctly:

SELECT User, Host, authentication_string FROM mysql.user WHERE User = 'new_user';

3.1 如何创建新用户?

CREATE USER 'user'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON datebase.table TO 'dbuser'@'%'; -- 可以细设置权限,安全
FLUSH PRIVILEGES;

3.2 查看与修改用户权限

1. 登录到 MySQL

用具有管理员权限的用户(例如 root)登录到 MySQL:

mysql -u root -p

2. 授予权限

为用户 hk416hasu 授予 learn 数据库的访问权限。

  1. 如果你想授予所有权限:

    GRANT ALL PRIVILEGES ON learn.* TO 'hk416hasu'@'%';
    FLUSH PRIVILEGES;
    
    • learn.* 表示授予 learn 数据库中所有表的权限。
    • @'%' 表示允许从任何 IP 地址访问。
  2. 如果只想授予基本的查询权限(安全性更高):

    GRANT SELECT ON learn.* TO 'hk416hasu'@'%';
    FLUSH PRIVILEGES;
    

3. 验证权限

可以验证用户的权限:

SHOW GRANTS FOR 'hk416hasu'@'%';

希望有解决你的问题!😄

posted @ 2024-12-15 20:24  hk416hasu  阅读(13)  评论(0编辑  收藏  举报