0

I do not understand why I can connect to a Mysql DB via SSH and Sequel Pro but if I am trying this with Python I can't establish a connection.

Everything works fine when I open Sequel Pro and filling the following data in the boxes:

MySQL-Host: 127.0.0.1
User: db_username
Password: db_password
Database: database
Port: 3306

SSH-Host: ssh_ip_adress
SSH-User: ssh_user
SSH-Password: ssh_password
SSH-Port: 22 

but when I try this in Python

   import pymysql
   from sshtunnel import SSHTunnelForwarder

   with SSHTunnelForwarder(
            ('ssh_ip_adress', 22),
            ssh_username="ssh_user",
            ssh_password="ssh_password",
            remote_bind_address=(127.0.0.1, 3306)
    ) as tunnel:
        port = tunnel.local_bind_port
        db_connection = pymysql.connect(
        host='ssh_ip_adress', port=port, db='database', user='db_username',
        password='db_password', charset='utf8mb4')

I receive an error:

sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway

What can I do?

naheliegend
  • 159
  • 2
  • 3
  • 9
  • Is `ssh_ip_adress` literally "ssh_ip_adress", or the IP of the remote system? Then you're trying to connect with MySQL to the SSH IP address…? That won't work. You need to connect to the locally bound SSH port. – deceze Oct 28 '20 at 09:15
  • I don't know why that fails, but you can connect with sqlalchemy if it's ok for you. You can also take a look [here](https://stackoverflow.com/questions/21903411/enable-python-to-connect-to-mysql-via-ssh-tunnelling) – SergioGM Oct 28 '20 at 09:17
  • @deceze what should I change in my python code? the ssh_ip_adress ist the ip from the remote server. – naheliegend Oct 28 '20 at 10:55
  • I don't have any first-hand experience with `SSHTunnelForwarder`, but the idea is that the SSH tunnel binds a *local* port on your machine which causes all traffic put into it to fall out the MySQL port on the remote machine. So you're going to connect with your MySQL client to the bound local port (and the tunnel will transparently forward that to the remote MySQL). You don't connect the MySQL client to the remote machine (because then you're bypassing the established tunnel entirely). – deceze Oct 28 '20 at 10:58
  • @deceze so should I use a local_bind_adress or what? 0.0.0.0:22 or what? – naheliegend Oct 28 '20 at 13:33
  • Probably `'localhost', tunnel.local_bind_port`. – deceze Oct 28 '20 at 13:40

0 Answers0