通过python脚本连接AWS DocumentDB的问题-使用SSH隧道

wtzytmuj  于 2023-04-08  发布在  Python
关注(0)|答案(1)|浏览(154)

我正在尝试使用pymongo从我的本地计算机连接到我们的AWS DocumentDB示例。我们当前的设置是在ec2示例上使用ssh隧道,然后连接到AWS DocumentDB。这部分工作正常,因为我可以通过第三方工具连接到它。(例如Studio 3 T-创建用户没有问题)。
在每个第三方工具中,我都上传了rds-combined-ca-bundle.pem文件,我想这可能是我卡住的地方。
隧道根据bastion主机上的日志工作。
我已经尝试了下面代码的几个变体,但它只是超时。
目前使用的是Pymongo 4.3.3版本。
此外,对于其他信息,我想在我的桌面上测试这一点,但最终将其移动到Lambda。
任何帮助是非常感谢!!
当前代码-

import pymongo
import sshtunnel

global_pem_key="c:\\users\\user\\pathto\\rds-combined-ca-bundle.pem"
ssh_host = 'external IP'
ssh_username = 'sshUser'

database_username = 'Uname'
database_password = 'Pword'
database_name = 'dbname'

tunnel = sshtunnel.SSHTunnelForwarder(
    (ssh_host, 22),
    ssh_username=ssh_username,
    ssh_pkey="c:\\users\\user\\path\\sshpemkey",
    remote_bind_address=('127.0.0.1', 3306)
)

tunnel.start()

client=pymongo.MongoClient("mongodb://dbuname:dbpass@dbName.cluster-***.*-*-*.docdb.amazonaws.com:27017/?ssl=true&ssl_ca_certs=rds-combined-ca-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false",
                            tlsInsecure=True,
                            directConnection=True,
                            tls=True,
                           tlsCAFile='c:\\users\\user\\\dpath\\rds-combined-ca-bundle.pem'

                            )

print(client.list_database_names())

tunnel.close()
fhity93d

fhity93d1#

试试这个代码片段:

import pymongo
import sshtunnel

# SSH variables
ssh_host = 'myec2.compute.amazonaws.com'
ssh_port = 22
ssh_user = 'ec2-user'
ssh_key = 'path_to_my_ssh_key.pem'

# DocDB variables
docdb_username = 'mydocdb_user'
docdb_password = 'mydocdb_pass'
database_name = 'test'
docdb_endpoint = 'dbName.cluster-***.*-*-*.docdb.amazonaws.com'
docdb_port = 27017
docdb_pem = 'path_to/rds-combined-ca-bundle.pem'

with sshtunnel.SSHTunnelForwarder(
        (ssh_host, ssh_port),
        ssh_username=ssh_user,
        ssh_pkey=ssh_key,
        local_bind_address=('127.0.0.1', 27017),
        remote_bind_address=(docdb_endpoint, docdb_port)) as tunnel:
    docdb_client = pymongo.MongoClient(
        host=tunnel.local_bind_host,
        port=tunnel.local_bind_port,
        tls=True,
        tlsInsecure=True,
        retryWrites=False,
        tlsCAFile=docdb_pem,
        directConnection=True,
        username=docdb_username,
        password=docdb_password,
        authSource='admin'
        )
    print(docdb_client.list_database_names())
    docdb_client.close()

相关问题