gpt4 book ai didi

Python SSH 隧道进入 EC2 并连接到 DocumentDB

转载 作者:行者123 更新时间:2023-12-04 14:10:30 25 4
gpt4 key购买 nike

我一直在尝试通过 SSH 隧道连接到 EC2 实例并连接到位于同一 VPC 中的 DocumentDB。我已经尝试了所有可以在线挖掘的解决方案,但没有运气。我正在使用 ssh_pymongo 模块,它包装了 SSHTunnelForwarder。我能够直接通过 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 个月后你会找到一个解决方案,但我会把这个留在这里给其他有同样问题的人

关于Python SSH 隧道进入 EC2 并连接到 DocumentDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64828294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com