Linux Ubuntu MySQL remote access 远程连接配置

本文介绍了如何解决MySQL默认不支持远程访问的问题。首先需要编辑配置文件,取消对本地地址的绑定,或者更改绑定地址为远程服务器IP。其次,创建允许远程访问的账号,并赋予相应的权限。最后重启MySQL服务使更改生效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

For security consideration, mySQL does NOT allow remote access by default. 

You might see err: Can't connect to MySQL server on 'xx.xx.xx.xx'(10061)

Please check below configurations:

==========================

1. Listen to remote servers

vi /etc/mysql/my.cnf

# Instead of skip-networking the default is now to listen only on  

# localhost which is more compatible and is not less secure.  

bind-address = 127.0.0.1

comment out above line, or change to your remote server IP.

==========================

2. Create an account for remote access. (by default root account can only be used locally.)

# mysql -u root -proot 

mysql>GRANT ALL PRIVILEGES ON *.* TO 'sa'@'%' IDENTIFIED BY 'youpassword' WITH GRANT OPTION;

mysql>flush privileges;

# service mysql restart

 

转载于:https://www.cnblogs.com/anbosun/p/6010024.html

<think>我们已经在之前的回答中介绍了如何测试单个MySQL数据库连接。现在用户希望测试多个MySQL数据库连接。我们可以扩展之前的方法,通过编写脚本或使用循环来测试多个连接。 ### 方法1:使用循环在命令行中测试多个连接 我们可以将多个数据库连接信息存储在一个配置文件中,然后通过循环读取配置并测试每个连接。 #### 步骤: 1. **创建一个配置文件**(例如`db_connections.txt`),每行定义一个数据库连接,格式为:`host:port:user:password`(注意:密码明文存储有安全风险,仅用于测试环境) ``` 192.168.1.100:3306:user1:pass1 192.168.1.101:3306:user2:pass2 10.0.0.5:3307:admin:admin123 ``` 2. **编写测试脚本**(例如`test_multi_mysql.sh`): ```bash #!/bin/bash # 读取配置文件 while IFS=: read -r host port user password do echo "Testing connection to $host:$port ..." # 使用mysql命令测试连接 if mysql -h "$host" -P "$port" -u "$user" -p"$password" -e "SELECT 1;" >/dev/null 2>&1; then echo "Connection to $host:$port succeeded." else echo "Connection to $host:$port failed." fi done < db_connections.txt ``` 3. **运行脚本**: ```bash chmod +x test_multi_mysql.sh ./test_multi_mysql.sh ``` **注意**:在命令行中直接使用密码会有安全风险(密码可能被其他用户通过`ps`命令看到),建议在测试环境中使用,或使用MySQL选项文件(`~/.my.cnf`)来存储密码。 ### 方法2:使用MySQL选项文件(更安全) 1. **为每个连接创建选项文件**(例如`~/.mylogin.cnf`,但更安全的方式是为每个连接创建单独的配置文件,并在脚本中指定) 我们可以创建多个配置文件,每个配置文件对应一个数据库连接。 - 创建配置文件`db1.cnf`: ```ini [client] host=192.168.1.100 port=3306 user=user1 password=pass1 ``` - 创建配置文件`db2.cnf`: ```ini [client] host=192.168.1.101 port=3306 user=user2 password=pass2 ``` 2. **编写脚本测试多个连接**: ```bash #!/bin/bash # 定义配置文件数组 config_files=("db1.cnf" "db2.cnf") for config in "${config_files[@]}" do host=$(grep -m1 '^host=' "$config" | cut -d= -f2) port=$(grep -m1 '^port=' "$config" | cut -d= -f2) echo "Testing connection to $host:$port ..." if mysql --defaults-file="$config" -e "SELECT 1;" >/dev/null 2>&1; then echo "Connection to $host:$port succeeded." else echo "Connection to $host:$port failed." fi done ``` ### 方法3:使用编程语言(如Python) 如果需要更复杂的测试,可以使用编程语言编写脚本。以下是一个使用Python的示例: 1. **安装Python MySQL连接器**: ```bash pip install mysql-connector-python ``` 2. **编写Python脚本**(例如`test_multi_mysql.py`): ```python import mysql.connector from mysql.connector import Error # 定义连接列表 connections = [ {"host": "192.168.1.100", "port": 3306, "user": "user1", "password": "pass1"}, {"host": "192.168.1.101", "port": 3306, "user": "user2", "password": "pass2"}, {"host": "10.0.0.5", "port": 3307, "user": "admin", "password": "admin123"} ] for conn in connections: try: connection = mysql.connector.connect( host=conn["host"], port=conn["port"], user=conn["user"], password=conn["password"] ) if connection.is_connected(): print(f"Connection to {conn['host']}:{conn['port']} succeeded.") connection.close() except Error as e: print(f"Connection to {conn['host']}:{conn['port']} failed: {e}") ``` 3. **运行脚本**: ```bash python test_multi_mysql.py ``` ### 注意事项 1. **安全**:避免在脚本中硬编码密码,尤其是生产环境。可以使用加密的密码存储或环境变量。 2. **错误处理**:在脚本中处理连接失败的情况,并输出有意义的错误信息。 3. **网络问题**:确保测试机器与目标MySQL服务器之间的网络连通性(使用`ping`或`telnet`测试端口)。 ### 相关问题 1. 如何在Linux中安全地存储MySQL连接密码? 2. 如何使用SSH隧道连接远程MySQL数据库? 3. 如何批量管理多个MySQL服务器? 4. 如何监控多个MySQL数据库的运行状态? 5. 在Linux下如何自动化测试多个数据库连接? 通过以上方法,您可以灵活地测试多个MySQL数据库连接,并根据需求选择最适合的方式[^1][^2][^3]。</think>### 如何在 Linux 下测试多个 MySQL 数据库连接 以下是测试多个 MySQL 数据库连接的完整方案,包含三种实用方法: --- #### 方法 1:使用 Shell 脚本批量测试(推荐) ```bash #!/bin/bash # 定义数据库连接数组 declare -A dbs=( ["db1"]="mysql -h 192.168.1.100 -u user1 -pPass123 -P 3306" ["db2"]="mysql -h db2.example.com -u admin -pAdmin@456 -P 3307" ["db3"]="mysql -h 10.0.0.5 -u readonly -pReadOnly789 -P 3306" ) # 循环测试所有连接 for db in "${!dbs[@]}"; do echo -n "测试 $db 连接... " if ${dbs[$db]} -e "SELECT 1;" &>/dev/null; then echo -e "\033[32m成功\033[0m" else echo -e "\033[31m失败\033[0m" # 获取详细错误信息 ${dbs[$db]} -e "SELECT 1;" 2>&1 | head -n 1 fi done ``` **使用步骤:** 1. 将脚本保存为 `test_dbs.sh` 2. 修改权限:`chmod +x test_dbs.sh` 3. 执行测试:`./test_dbs.sh` **输出示例:** ``` 测试 db1 连接... 成功 测试 db2 连接... 失败 ERROR 1045 (28000): Access denied for user 'admin'@'client-ip' (using password: YES) 测试 db3 连接... 成功 ``` --- #### 方法 2:使用 nmap 扫描多主机端口 ```bash # 安装 nmap sudo apt install nmap # Ubuntu/Debian sudo yum install nmap # CentOS/RHEL # 扫描多个 MySQL 端口 nmap -p 3306,3307,3308 192.168.1.100 db2.example.com 10.0.0.5 ``` **输出示例:** ``` Starting Nmap 7.80... Host: 192.168.1.100 3306/tcp open mysql Host: db2.example.com 3307/tcp open mysql Host: 10.0.0.5 3306/tcp filtered mysql # 表示端口被防火墙拦截 ``` --- #### 方法 3:Python 脚本测试(带详细诊断) ```python #!/usr/bin/python3 import mysql.connector from mysql.connector import Error dbs = [ {"name": "主数据库", "host": "192.168.1.100", "user": "user1", "password": "Pass123", "port": 3306}, {"name": "备份数据库", "host": "db2.example.com", "user": "admin", "password": "Admin@456", "port": 3307}, {"name": "分析数据库", "host": "10.0.0.5", "user": "readonly", "password": "ReadOnly789", "port": 3306} ] for db in dbs: try: conn = mysql.connector.connect( host=db["host"], user=db["user"], password=db["password"], port=db["port"], connection_timeout=3 # 设置超时时间 ) cursor = conn.cursor() cursor.execute("SELECT @@version, @@hostname") result = cursor.fetchone() print(f"[✓] {db['name']} 连接成功 | MySQL版本: {result[0]} | 主机名: {result[1]}") cursor.close() conn.close() except Error as e: print(f"[✗] {db['name']} 连接失败 | 错误: {e}") ``` **使用步骤:** 1. 安装驱动:`pip install mysql-connector-python` 2. 保存为 `test_multi_db.py` 3. 执行:`python3 test_multi_db.py` --- ### 常见问题排查指南 | 错误代码 | 原因 | 解决方案 | |---------|------|---------| | **ERROR 1045** | 权限不足 | 执行授权命令:<br>`GRANT ALL ON *.* TO 'user'@'%' IDENTIFIED BY 'password';`<br>`FLUSH PRIVILEGES;` [^1] | | **ERROR 2003** | 端口不通 | 1. 检查防火墙:`sudo ufw allow 3306/tcp`<br>2. 修改 MySQL 配置:`bind-address = 0.0.0.0` | | **ERROR 2013** | 连接超时 | 1. 检查网络路由<br>2. 增加超时时间:`mysql --connect-timeout=30` | | **ERROR 1040** | 连接数超限 | 修改 `max_connections` 值:<br>`SET GLOBAL max_connections=500;` | --- ### 安全建议 1. 使用 `mysql_config_editor` 安全存储凭证: ```bash mysql_config_editor set --login-path=db1 \ --host=192.168.1.100 --user=admin --port=3306 mysql --login-path=db1 -e "SHOW DATABASES" ``` 2. 通过 SSH 隧道加密连接: ```bash ssh -L 63306:remote-db:3306 user@remote-server mysql -h 127.0.0.1 -P 63306 -u dbuser -p ``` 3. 定期轮换数据库密码 4. 使用最小权限原则分配数据库账户 --- ### 相关问题 1. 如何批量管理多个 MySQL 服务器的用户权限? 2. 在 Linux 中如何自动化监控多个 MySQL 实例的状态? 3. 使用 SSH 隧道连接 MySQL 时如何避免端口冲突? 4. 如何为不同的 MySQL 连接配置不同的超时时间? 5. MySQL 连接池的最佳实践是什么? [^1]: 需要为每个数据库单独创建用户并授权[^1] [^2]: 复杂环境可使用 ODBC 统一管理连接[^2] [^3]: Python 等语言可通过 JDBC 驱动连接[^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值