无法在AWS上的EC2与Python中的SSHTunnelForwarder之间进行连接

问题描述

前提

我正在用两个AWS账户构建EC2,让我们叫一个A,另一个B. RDS也是内置在B中的。目的是从A开始启动Python,并使用B作为连接RDS的垫脚石。

在每个入站规则和出站规则中,端口号22和3306、443和80设置为0.0.0.0/0。问题消失后,我会修复它。

代码

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)

错误消息

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

我尝试过的

  1. 将相应源代码host=更改为A的IP地址,但是发生了相同的错误

  2. 我像3306和3305一样划分了remote_bind_address=local_bind_address=的端口号,并根据local_bind_address设置了port=,但这没用。

  3. 我确认使用B作为此来源的垫脚石,从本地PC到RDS的连接。

最后,我认为英语不好,很难阅读,但谢谢您阅读。

解决方法

唯一缺少的部分是调整 MySQL 连接中的端口,如下所示。

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)