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

标签 python mongodb amazon-web-services ssh pymongo

我一直在尝试通过 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/

相关文章:

amazon-web-services - 没有存储桶策略的 s3 预签名 url 不起作用

amazon-web-services - EMR 上 Hadoop 作业的 S3 文件的最佳文件大小?

python - @method_decorator(csrf_exempt) NameError : name 'method_decorator' is not defined

MongoDB 列出父类别中的子类别

javascript - 子类化 Meteor.users() 以获得不同的用户类型

linux - 删除所有附加卷后再次启动 Amazon EC2 实例

python - 当我尝试使用 pika (python) 向 RabbitMQ 确认消息时发生错误 "unknown delivery tag"

python - wx.Gauge在Windows中无法更新超过25%,在Linux中有效

python - 如何找到不同值的坐标?

node.js - Mongoose 级联创建/删除集合的好方法