簡體   English   中英

Python SSH 隧道進入 EC2 並連接到 DocumentDB

[英]Python SSH tunnel into EC2 and connect to DocumentDB

我一直在嘗試將 SSH 隧道連接到 EC2 實例並連接到位於同一 VPC 中的 DocumentDB。 我已經嘗試了所有我可以在網上找到的解決方案,但沒有運氣。 我正在使用包裝 SSHTunnelForwarder 的 ssh_pymongo 模塊。 我能夠將 SSH 直接插入 EC2 實例並連接到 DocumentDB 集群。 我試圖通過 python 來實現同樣的目標。

示例代碼:

from ssh_pymongo import MongoSession

session = MongoSession(
    host='ec2-x-x-x-x.region.compute.amazonaws.com',
    port=22,
    user='ec2-user', # The user ec2-user is specific to EC2 instance OS Amazon Linux 2
    key='key.pem',
    uri='mongodb://<username>:<password>@xxxxx-docdb-cluster.cluster-xxxxxxxxxxxxx.region.docdb.amazonaws.com:27017'
)

# Note for the above function call: I've also tried various combinations of the to_host and to_port params without success.

db = session.connection['db-name']

print(db.collection_names())

錯誤:

Could not establish connection from local ('127.0.0.1', 36267) to remote ('xxxxx-docdb-cluster.cluster-xxxxxxxxxxxx.region.docdb.amazonaws.com', 27017) side of the tunnel: open new channel ssh error: Timeout opening channel.

我也嘗試過 ssh_pymongo 模塊,但沒有成功。 但是,我直接嘗試使用 sshtunnel 模塊,並且能夠查詢我的數據庫。

這是我的代碼

from sshtunnel import SSHTunnelForwarder
from pymongo import MongoClient

# VM IP/DNS - Will depend on your VM
EC2_URL = '''*.*.compute.amazonaws.com'''

# Mongo URI Will depende on your DocDB instances
DB_URI = '''dbname.*.*.docdb.amazonaws.com'''

# DB user and password
DB_USER = 'dbuser'
DB_PASS = 'dbpassword'

# Create the tunnel
server = SSHTunnelForwarder(
    (EC2_URL, 22),
    ssh_username='ubuntu',                # I used an Ubuntu VM, it will be ec2-user for you
    ssh_pkey='~/.ssh/keypair.pem',   # I had to give the full path of the keyfile here
    remote_bind_address=(DB_URI, 27017),
    local_bind_address=('127.0.0.1', 27017)
)
# Start the tunnel
server.start()

# Connect to Database
client = MongoClient(
    host='127.0.0.1',
    port=27017,
    username='DB_USER',
    password='DB_PASS'
)


# Close the tunnel once you are done
server.stop()

我想 3 個月后你會找到一個解決方案,但我會把這個留在這里給其他有同樣問題的人

不斷收到此錯誤

pymongo.errors.ServerSelectionTimeoutError: SSL handshake failed: document_db_server:27017: 
[Errno 54] Connection reset by peer,SSL handshake failed: document_db_server:27017: 
[Errno 54] Connection reset by peer, Timeout: 2.0s, Topology Description: 
<TopologyDescription id: 63121b21cc3688a700cc86f9, topology_type: ReplicaSetNoPrimary, 
servers: [<ServerDescription ('document_db_server', 27017) server_type: Unknown, rtt: None>, 
<ServerDescription ('document_db_server', 27017) 
server_type: Unknown, rtt: None, error=AutoReconnect('SSL handshake failed: document_db_server:27017: 
[Errno 54] Connection reset by peer')>, <ServerDescription ('document_db_server', 27017) 
server_type: Unknown, rtt: None, error=AutoReconnect('SSL handshake failed: document_db_server:27017: 
[Errno 54] Connection reset by peer')>]>

解決方案是將 directConnection directConnection=True添加到MongoClient

port = 27017
server = SSHTunnelForwarder(
            (ec2_ip, 22),
            ssh_username=ec2_user,
            ssh_pkey=ec2_pem_key,
            remote_bind_address=(document_db_server, port),
            local_bind_address=('127.0.0.1', port)

        )
server.skip_tunnel_checkup = False
server.start()
server.check_tunnels()
print(f"Tunnel is Up {server.tunnel_is_up}")
print(f"Local is up {server.local_is_up(('0.0.0.0', port))}")
print('---------------TUNNEL IS ESTABLISHED----------------')

"""DOCUMENT DB CONNECTION"""
client = pymongo.MongoClient(
        host="mongodb://127.0.0.1:27017/?",
        tls=True,
        username=documentdb_user,
        password=documentdb_password,
        authMechanism="SCRAM-SHA-1",
        tlsCAFile=document_db_ca_pem_file,
        tlsAllowInvalidHostnames=True,
        timeoutMS=10000,
        directConnection=True
      )

希望這會幫助某人

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM