Python MySQL与SSH的连接

2024-05-15 23:11:06 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我买了一个共享主机,它只允许使用SSH进行远程MySQL连接

到目前为止,我知道它没有任何公钥或私钥

下面是我在MySQL工作台上的连接设置,当我尝试连接时,它会起作用:

enter image description here

我已经看了另一个stackoverflow问题:Here但是没有一个答案对我有效我真的走到了死胡同,我需要让这一切正常运作。有人能帮我吗


Tags: 答案远程heremysqlstackoverflowssh私钥公钥
2条回答
  1. 通过ssh和端口转发连接到服务器198.54.x.240:21098ssh -t -gL 33069:localhost:3306 198.54.x.240 在窗户上用油灰,我喜欢基蒂(叉子油灰) 添加连接和SSH隧道查看图片 create_connectionadd ssh tunneladd port to forward
  2. 通过localhost:33069(answer you know)WorkBench连接到MySQL也可以这样做,但是3306在3306上,如果您需要一个以上的远程连接最佳实践转发不同的porst

所以我用了一百万次的尝试和错误来解决这个问题:

import pymysql
import paramiko
import pandas as pd
from paramiko import SSHClient
from sshtunnel import SSHTunnelForwarder

ssh_host = '198.54.xx.xx'
ssh_host_port = 21098 #Ur SSH port
ssh_username = "sshuser123" #Change this
ssh_password = "sshpassword123" #Change this

db_user = 'db user' #change this
db_password = 'password123' #change this
db = 'main_db' #The db that the user is linked to


with SSHTunnelForwarder(
        (ssh_host, ssh_host_port),
        ssh_username=ssh_username,
        ssh_password=ssh_password,
        remote_bind_address=('127.0.0.1', 3306)) as tunnel:
    conn = pymysql.connect(host='127.0.0.1', user=db_user,
            passwd=db_password, db=db,
            port=tunnel.local_bind_port)
    query = '''SELECT * from tablename;'''
    data = pd.read_sql_query(query, conn)
    print(data)
    conn.close()

如果MySql上的SSH没有任何公钥/私钥,则应使用此代码

希望这能帮助任何面临同样问题的人

相关问题 更多 >