SSH(Secure Shell)是一种加密的网络协议,用于在不安全的网络上安全地执行远程命令和传输数据。MySQL是一种流行的关系型数据库管理系统,广泛用于Web应用程序的数据存储。
SSH连接MySQL数据库主要有两种方式:
原因:
解决方法:
原因:
解决方法:
/etc/ssh/sshd_config
),确保以下配置项未被注释且设置为yes
:/etc/ssh/sshd_config
),确保以下配置项未被注释且设置为yes
:/etc/my.cnf
或/etc/mysql/my.cnf
),确保以下配置项未被注释且设置为0.0.0.0
:/etc/my.cnf
或/etc/mysql/my.cnf
),确保以下配置项未被注释且设置为0.0.0.0
:以下是一个通过SSH隧道连接MySQL数据库的示例代码:
import mysql.connector
from sshtunnel import SSHTunnelForwarder
# SSH连接信息
ssh_host = 'your_ssh_host'
ssh_port = 22
ssh_username = 'your_ssh_username'
ssh_password = 'your_ssh_password'
# MySQL连接信息
mysql_host = '127.0.0.1'
mysql_port = 3306
mysql_user = 'your_mysql_user'
mysql_password = 'your_mysql_password'
mysql_database = 'your_mysql_database'
# 创建SSH隧道
with SSHTunnelForwarder(
(ssh_host, ssh_port),
ssh_username=ssh_username,
ssh_password=ssh_password,
remote_bind_address=(mysql_host, mysql_port)
) as tunnel:
# 连接到MySQL数据库
conn = mysql.connector.connect(
host='127.0.0.1',
port=tunnel.local_bind_port,
user=mysql_user,
password=mysql_password,
database=mysql_database
)
# 执行查询
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table")
results = cursor.fetchall()
for row in results:
print(row)
# 关闭连接
cursor.close()
conn.close()
领取专属 10元无门槛券
手把手带您无忧上云