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

连接Azure IoT Hub时出现SSL Wrong Version Error问题求助

解决Azure IoT Hub间歇性SSL版本错误问题(Python 3.12.2 + azure-iot-device 2.13.0)

可能的核心原因

  • Python 3.12.x默认SSL配置和azure-iot-device 2.13.0存在兼容性冲突,新版本Python对TLS版本的限制更严格,而IoT Hub部分节点的TLS协商逻辑未完全适配。
  • 长时间循环运行时,连接池复用或自动重连过程中,TLS版本协商容易出现异常,导致间歇性报错。

针对性修复方案

1. 强制指定TLS版本

初始化客户端前手动配置SSL上下文,锁定IoT Hub推荐的TLS 1.2版本,避免自动协商出错:

import ssl
from azure.iot.device import IoTHubDeviceClient, Message

# 自定义SSL上下文,强制禁用低版本TLS
ctx = ssl.create_default_context()
ctx.set_ciphers('DEFAULT@SECLEVEL=1')
ctx.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1

# 初始化客户端时传入上下文
client = IoTHubDeviceClient.create_from_connection_string(
    "你的设备连接字符串",
    ssl_context=ctx
)

2. 手动优化重连逻辑

默认重连机制在长时间运行时可能失效,添加断开回调和主动重连逻辑:

import time

def on_disconnect():
    print("连接断开,尝试重连...")
    try:
        client.connect()
    except Exception as e:
        print(f"重连失败: {e}")

# 设置断开回调
client.on_disconnect = on_disconnect

# 循环中捕获SSL异常并主动重连
while True:
    try:
        # 替换成你的收发消息逻辑
        msg = Message("测试消息")
        client.send_message(msg)
        print("消息发送成功")
        time.sleep(5)
    except ssl.SSLError as e:
        if "wrong version number" in str(e):
            print("触发SSL版本错误,主动重连")
            client.disconnect()
            client.connect()
        else:
            raise
    except Exception as e:
        print(f"其他异常: {e}")
        time.sleep(10)

3. 锁定兼容依赖版本

除了urllib3=1.26.5,补充锁定cryptography版本,避免SSL底层库兼容性问题:
在requirements.txt中添加:

azure-iot-device==2.13.0
urllib3==1.26.5
cryptography==39.0.1

4. 禁用连接池复用(极端情况)

如果以上方法无效,尝试强制每次请求新建连接,避免旧连接的SSL状态异常:

from azure.iot.device.transport.http import HttpTransport

transport = HttpTransport(
    connection_string="你的设备连接字符串",
    ssl_context=ctx,
    connection_pool_size=1  # 关闭连接池复用
)
client = IoTHubDeviceClient(transport=transport)

调试建议

开启SSL调试日志,观察异常发生时的TLS协商细节:

import logging
logging.basicConfig(level=logging.DEBUG)

重点关注日志中ssl相关条目,确认是否是版本协商阶段出现不匹配。

内容的提问来源于stack exchange,提问作者Lu Wan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:25:58