从Python连接MongoDB Atlas时SSL握手失败

0 投票
2 回答
76 浏览
提问于 2025-04-14 18:35

我正在使用pymongo库通过以下Python代码连接到MongoDB Atlas:

我已经尝试更换网络环境,并确认我的Atlas集群正常运行,没有任何维护工作会影响连接。下面是我用来建立连接的Python代码:

from pymongo import MongoClient, server_api
import certifi

# MongoDB Atlas connection URI
uri = 'mongodb+srv://<username>:<password>@<cluster-address>/?retryWrites=true&w=majority&appName=TaipeiYouBikeHourlyData'

# Use the certifi library to get the path of the CA certificate
ca = certifi.where()

try:
    # Create a MongoClient instance and specify the CA certificate path
    client = MongoClient(uri, server_api=server_api.ServerApi('1'), tlsCAFile=ca)
    
    # Send a ping command to test the connection
    response = client.admin.command('ping')
    print("Successfully connected to MongoDB, response:", response)

except Exception as e:
    print("Error connecting to MongoDB:", e)

我已经尝试过切换网络,确认我的MongoDB Atlas集群状态良好,并确保我的Python环境使用的是最新版本的必要库。但是,问题依然存在。

问题:

有没有人遇到过与MongoDB Atlas相关的SSL握手失败?你们是怎么解决的?有没有什么建议的故障排除步骤或配置我可能遗漏了?

2 个回答

0

我觉得我遇到的问题和我使用的WiFi网络有关系。在学校的时候,代码运行得很好,但在家里的WiFi上运行时就出错了。下面是我遇到问题的代码片段:

ctx = ssl.create_default_context()
ctx.check_hostname = False
client = MongoClient(uri, tls=True, tlsAllowInvalidCertificates=True, tlsCAFile=certifi.where())
try:
    client.admin.command('ping')
    print("Successfully connected to MongoDB!")
except Exception as e:
    print(f"Connection to MongoDB failed: {e}")

databases = client.list_database_names()
print("Databases:", databases)

尽管我尝试用这些设置来建立连接,但我还是无法在家里的网络上成功连接到MongoDB。

这个问题可能和我家里的WiFi设置或者网络限制有关,这些和学校的情况不一样,可能影响了SSL握手或者连接MongoDB的过程。

0

先确认一下问题是出在 tlsCAFile 还是网络上。TLS/SSL 是在一种叫做 TCP 的传输协议上运行的。可以先关闭 TLS,看看连接是否能建立:

ctx = ssl.create_default_context()
ctx.check_hostname = False
client = MongoClient(uri, server_api=server_api, tlsContext=sslContext)

如果这时候连接没有失败,那就说明问题可能出在你的登录凭证上。如果凭证是正确的,并且你也安装了最新版本的 certifi,那就要检查一下你的防火墙。MongoDB Atlas 是在 AWS 上运行的,所以它是在一个虚拟私有云(VPC)里。这个 VPC 里面可以有公共子网或者私有子网。即使是在公共子网里,安全组是否开放?你能 ping 通 27017 吗?

这个错误可能有很多原因,但可以通过排除法来找出问题所在。

撰写回答