简体   繁体   中英

Python MySQL Connection with SSH

Hi I have a shared hosting i bought and it allows for remote MySQL connection only with SSH.

So far I know that it doesn't have any Public or Private Keys..

And here's my connection setup on the MySQL Workbench which works when I try to connect:

在此处输入图像描述

I have looked at another stackoverflow question: Here but none of the answers seems to work for me.. :/ I'm really at a dead end and I need to get this to work. Can someone help me out please?

So I figured it out with like a million trial and error:

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()

This is the code you should use if your SSH on MySql doesn't have any Public / Private Key.

Hope this helps anyone facing the same issue!!

  1. Connect to server 198.54.x.240:21098 via ssh with port-forwarding like ssh -t -gL 33069:localhost:3306 198.54.x.240 in windows use PuTTY, i like KiTTy (fork putty ) add connection and SSH Tunnel look at the pictures 创建连接 添加 ssh 隧道 添加端口转发
  2. Connect to MySQL via localhost:33069 ( answer you know )WorkBench do the same, but 3306 on 3306, if you need more than 1 remote connection best practice forward different porst.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM