pahaz / sshtunnel

SSH tunnels to remote server.
MIT License
1.23k stars 184 forks source link

Having a problem connecting to MySQL database using SSHTunnel (Its probably me) #241

Open razorblade23 opened 3 years ago

razorblade23 commented 3 years ago

I have a web app that uses MySQL database to store data, and its running locally (Python, Flask). I now have access to private server and i have SSH access. I have made a SSH pkey and i am able to connect using terminal with server and also able to get in mysql console.

Problem is when i try to make connection with database from my app, it says

Can't connect to MySQL server on '127.0.0.1'

here is my code for using tunnel and SQL alchemy

with sshtunnel.SSHTunnelForwarder( 'HOST_URL', ssh_username='SSH_USERNAME', remote_bind_address=('HOST_URL', 3306), local_bind_address=('0.0.0.0', 33066), ssh_pkey='id_rsa', ssh_private_key_password='MY_PRIVATE_KEY_PASS' ) as tunnel: tunnel.start() app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://username:password@127.0.0.1:33066/smartaku_smartdarts_test'

judeleonard commented 8 months ago

Posting this here for future debuggers. Actually you do not need an id_rsa to ssh into a server and connect to your database. Here is the command I use for such cases:

with SSHTunnelForwarder(
    (ssh_ip_address), 
    ssh_username = ssh_username,
    ssh_password = ssh_password,
    remote_bind_address=(db_host, db_port)) as server: 

   #start ssh sever
    server.start() 
    print('Server connected via SSH')

    #connect to PostgreSQL
    local_port = str(server.local_bind_port)
    engine = create_engine('postgresql://db_user:db_password@db_host:' + local_port +'/db_name')

    Session = sessionmaker(bind=engine)
    session = Session()
    print('Database session created')

    #connect and run query
    query = """
        SELECT * FROM table_name
    """
    conn = engine.connect().connection
    with conn.cursor() as cur:
            cur.copy_expert(sql=query)        
    conn.commit()

note: db_host=localhost