Unable to connect between EC2 on AWS with SSHTunnelForwarder in Python

Viewed 614

Premise

I'm building EC2 with two AWS accounts.Let's call one A and the other B. RDS is also built in B. The purpose is to start Python from A and use B as a stepping stone to connect to RDS.

In each inbound rule and outbound rule, the port numbers 22 and 3306, 443 and 80 are set to 0.0.0.0/0. I will fix it when the problem disappears.

Source Code

import mysql.connector
from sshtunnel import SSHTunnelForwarder

try:
    sshtunnel.SSH_TIMEOUT = 10.0

    with sshtunnel.SSHTunnelForwarder(
            ('IP address of B', 22),
            ssh_host_key=None,
            ssh_username='ec2-user',
            ssh_password=None,
            ssh_pkey='./XXXXXXXXX.pem',
            remote_bind_address=('RDS address of B', 3306),
            local_bind_address=('0.0.0.0', 3306)
    ) as tunnel:
        conn = mysql.connector.connect(
                host='127.0.0.1',
                port=3306,
                user='admin',
                db='XXXXXX',
                passwd='XXXXXX',
                charset="utf8"
        )

        c = conn.cursor()
        print(c)
        c.execute("SELECT * FROM XXXXXX ORDER BY Rand() LIMIT 50")

except Exception as e:
    print(e)

Error Message

Could not establish connection from ('IP address of B', 3306) to remote side of the tunnel

What I tried

  1. Changed the host= of the corresponding source code to the IP address of A, but the same error occurred.

  2. I divided the port numbers of remote_bind_address= and local_bind_address= like 3306 and 3305, and set the port= according to local_bind_address, but it didn't work.

  3. I confirmed the connection from the local PC to RDS using B as a stepping stone with this source.

Lastly, I think that English is not good and it is difficult to read, but thank you for reading.

1 Answers

The only missing piece was adjusting the port in the MySQL connection, as shown below.

import mysql.connector
from sshtunnel import SSHTunnelForwarder

try:
    sshtunnel.SSH_TIMEOUT = 10.0

    with sshtunnel.SSHTunnelForwarder(
            ('ec2-**-**-***-***.eu-central-1.compute.amazonaws.com', 22),
            ssh_host_key=None,
            ssh_username='ubuntu',
            ssh_password=None,
            ssh_pkey='./XXXXXXXXX.pem',
            remote_bind_address=('127.0.0.1', 3306)
    ) as tunnel:
        conn = mysql.connector.connect(
                host='127.0.0.1',
                port=tunnel.local_bind_port,
                user='admin',
                db='XXXXXX',
                passwd='XXXXXX',
                charset="utf8"
        )

        c = conn.cursor()
        print(c)
        c.execute("SELECT * FROM XXXXXX ORDER BY Rand() LIMIT 50")

except Exception as e:
    print(e)
Related