You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB SSL握手失败求助:跨机器异常交替出现

MongoDB SSL握手失败问题

每次执行查询操作时,均会触发MongoDB SSL握手失败错误。已在MongoDB网络访问配置中添加0.0.0.0/0的IP白名单,尝试更换用户、密码、登录信息及集群后,问题仍未解决。且该错误存在跨机器交替出现的异常情况:本地机器报错时其他机器可正常连接,其他机器报错时本地机器可正常运行。

代码实现

from pymongo import MongoClient
from dotenv import load_dotenv

import logging
import os

class Database:
    def __init__(self) -> None:
        os.system('cls' if os.name == 'nt' else 'clear')

        load_dotenv()

        DB_USER = os.getenv('DB_USER')
        DB_PASSWORD = os.getenv('DB_PASSWORD')
        DB_CLUSTER = os.getenv('DB_CLUSTER')
        
        try:
            connection_string = f"mongodb+srv://{DB_USER}:{DB_PASSWORD}@{DB_CLUSTER}.mongodb.net/"

            self.client = MongoClient(connection_string)
            self.db = self.client["IPs"]
            self.info = self.db["info"]

        except Exception as e:
            logging.error(f"Failed to connect to MongoDB: {e}")
            
    
    def getIPs(self):
        info = list(self.info.find({}))
        print(info)
        
        self.client.close()
        
if __name__ == "__main__":
    db = Database()
    db.getIPs()

报错信息

raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: SSL handshake failed: ac-ccnc26s-shard-00-00.gcolnp2.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms),SSL handshake failed: ac-ccnc26s-shard-00-02.gcolnp2.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms),SSL handshake failed: ac-ccnc26s-shard-00-01.gcolnp2.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout: 30s, Topology Description: <TopologyDescription id: 6636c72ea902572c1d2b9261, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-ccnc26s-shard-00-00.gcolnp2.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('SSL handshake failed: ac-ccnc26s-shard-00-00.gcolnp2.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>, <ServerDescription ('ac-ccnc26s-shard-00-01.gcolnp2.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('SSL handshake failed: ac-ccnc26s-shard-00-01.gcolnp2.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>, <ServerDescription ('ac-ccnc26s-shard-00-02.gcolnp2.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('SSL handshake failed: ac-ccnc26s-shard-00-02.gcolnp2.mongodb.net:27017: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:1006) (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>]>

解决方案

  • 指定TLS版本:MongoDB Atlas要求使用TLS 1.2及以上版本,部分旧环境默认TLS版本过低导致握手失败。修改MongoClient初始化代码,显式指定TLS版本:
    self.client = MongoClient(connection_string, tlsVersion='TLSv1.2')
    
  • 更新依赖库:旧版pymongo或dnspython可能存在SSL兼容问题,执行以下命令更新到最新版本:
    pip install --upgrade pymongo dnspython
    
  • 排查网络波动:交替出现的错误大概率和网络链路有关,比如ISP路由临时故障、防火墙/代理拦截。尝试切换网络(如WiFi转有线),或关闭本地防火墙、代理软件后重试。
  • 添加重试逻辑:针对网络波动导致的临时失败,在代码中增加重连机制,避免单次失败直接报错:
    from pymongo.errors import ServerSelectionTimeoutError
    import time
    
    class Database:
        def __init__(self) -> None:
            os.system('cls' if os.name == 'nt' else 'clear')
            load_dotenv()
    
            DB_USER = os.getenv('DB_USER')
            DB_PASSWORD = os.getenv('DB_PASSWORD')
            DB_CLUSTER = os.getenv('DB_CLUSTER')
            connection_string = f"mongodb+srv://{DB_USER}:{DB_PASSWORD}@{DB_CLUSTER}.mongodb.net/"
    
            max_retries = 3
            retry_count = 0
            self.client = None
            self.db = None
            self.info = None
    
            while retry_count < max_retries:
                try:
                    self.client = MongoClient(connection_string, tlsVersion='TLSv1.2')
                    self.db = self.client["IPs"]
                    self.info = self.db["info"]
                    break
                except ServerSelectionTimeoutError as e:
                    retry_count += 1
                    time.sleep(2)
                    if retry_count == max_retries:
                        logging.error(f"连接MongoDB失败,已重试{max_retries}次: {e}")
    

内容的提问来源于stack exchange,提问作者Leo Gotardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 20:22:05