在 Linux 系统中,MySQL 默认只允许本机访问,如果想要让其他机器远程访问 MySQL,需要开启 MySQL 的远程访问权限。具体步骤如下:
使用 vim 编辑 /etc/my.cnf 文件,内容如下:
[mysql] socket=/home/hxstrive/mysql5.7/mysql.sock default-character-set=utf8mb4 [mysqld] basedir=/home/hxstrive/mysql5.7 datadir=/home/hxstrive/mysql5.7/data # port=3306 # server_id=2 socket=/home/hxstrive/mysql5.7/mysql.sock default_storage_engine=innodb character-set-server=utf8mb4 collation-server=utf8mb4_bin lower_case_table_names=1 bind-address=127.0.0.1 sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES [mysqld_safe] log-error=/home/hxstrive/mysql5.7/data/mysqld.log pid-file=/home/hxstrive/mysql5.7/mysqld.pid
找到如下行:
bind-address = 127.0.0.1
如果没有,则在 [mysqld] 下面添加如下行:
bing-address = 127.0.0.1
如果允许所有机器访问,则将 127.0.0.1 修改为 0.0.0.0 或者直接将本行注释掉即可。
如果仅仅允许指定的机器访问,则将 127.0.0.1 修改为特定的 IP 地址。
[hxstrive@localhost mysql5.7]$ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 4 Server version: 5.7.40 MySQL Community Server (GPL) Copyright (c) 2000, 2022, Oracle and/or its affiliates. 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>
执行 “GRANT ALL PRIVILEGES ON *.* TO '用户名'@'访问IP' IDENTIFIED BY '密码' WITH GRANT OPTION;” 命令进行授权。其中,用户名为要创建的 MySQL 用户,访问 IP 为远程访问 MySQL 的 IP 地址或者使用 % 表示允许任何地址远程访问 MySQL。例如:
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'aaaaaa' WITH GRANT OPTION; Query OK, 0 rows affected, 1 warning (0.00 sec)
上面将授予 root 用户在任何机器上进行远程访问。
使用 “FLUSH PRIVILEGES” 刷新权限,例如:
mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)
[hxstrive@localhost mysql5.7]$ mysqladmin -h 127.0.0.1 -u root -p shutdown Enter password: 2023-09-18T05:07:26.541140Z mysqld_safe mysqld from pid file /home/hxstrive/mysql5.7/mysqld.pid ended
[hxstrive@localhost mysql5.7]$ mysqld_safe & 2023-09-18T05:05:37.816495Z mysqld_safe Logging to '/home/hxstrive/mysql5.7/data/mysqld.log'. 2023-09-18T05:05:37.918806Z mysqld_safe Starting mysqld daemon with databases from /home/hxstrive/mysql5.7/data