【问题标题】:Python SSH tunnel into EC2 and connect to DocumentDBPython SSH 隧道进入 EC2 并连接到 DocumentDB
【发布时间】:2021-07-20 12:50:33
【问题描述】:

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

【问题讨论】:

  • 你到底尝试了什么?你得到什么错误?
  • @Marcin 抱歉,让我将这些信息添加到原始问题中。
  • 超时通常意味着安全组有问题。您可以仔细检查它们或显示它们吗?
  • @Marcin 安全组不是问题,因为 SSH 对所有人开放,此外我还可以从同一系统手动 SSH。

标签: python mongodb amazon-web-services ssh pymongo


【解决方案1】:

我也尝试了 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 个月后您会找到解决方案,但我会将其留给有相同问题的其他人

【讨论】:

    猜你喜欢
    • 2023-02-10
    • 2021-10-24
    • 2021-05-02
    • 2021-05-03
    • 2017-09-28
    • 2014-03-21
    • 1970-01-01
    相关资源
    最近更新 更多