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

Python AsyncUA OPC UA客户端报错:BadSecureChannelIdInvalid

OPC UA客户端报错:BadSecureChannelIdInvalid 排查方案

使用Python AsyncUA库开发OPC UA客户端时,运行示例代码出现**The specified secure channel is no longer valid.(BadSecureChannelIdInvalid)**错误,最终程序以退出码1终止。

示例代码

import asyncio
from asyncua import Client

async def read_opcua_node(endpoint_url, node_id):
    async with Client(url=endpoint_url) as client:
        # Connect to the server
        await client.connect()

        # Read the node value
        node = await client.get_node(node_id)
        value = await node.read_value()

        # Print the result
        print(f"Value of node {node_id}: {value}")

if __name__ == "__main__":

    endpoint_url = "opc.tcp://172.10.0.13:4840"
    node_id = "ns=2;i=0"

    # Run the script
    asyncio.run(read_opcua_node(endpoint_url, node_id))

控制台报错信息

Requested session timeout to be 3600000ms, got 60000ms instead
Received an error: ErrorMessage(Error=StatusCode(value=2149711872), Reason=None)
Received an error: ErrorMessage(Error=StatusCode(value=2149711872), Reason=None)
Got error status from server: The specified secure channel is no longer valid.(BadSecureChannelIdInvalid)
close_secure_channel was called but connection is closed
disconnect_socket was called but connection is closed
close_session was called but connection is closed
close_secure_channel was called but connection is closed
disconnect_socket was called but connection is closed
Traceback (most recent call last):
  File "/Users/kavimuthurajas/PycharmProjects/Amber-OPCGateway/OPCUAClient.py", line 22, in <module>
    asyncio.run(read_opcua_node(endpoint_url, node_id))
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/Users/kavimuthurajas/PycharmProjects/Amber-OPCGateway/OPCUAClient.py", line 7, in read_opcua_node
    await client.connect()
  File "/Users/kavimuthurajas/PycharmProjects/Amber-OPCGateway/venv/lib/python3.11/site-packages/asyncua/client/client.py", line 310, in connect
    await self.create_session()
  File "/Users/kavimuthurajas/PycharmProjects/Amber-OPCGateway/venv/lib/python3.11/site-packages/asyncua/client/client.py", line 489, in create_session
    response = await self.uaclient.create_session(params)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/kavimuthurajas/PycharmProjects/Amber-OPCGateway/venv/lib/python3.11/site-packages/asyncua/client/ua_client.py", line 335, in create_session
    data = await self.protocol.send_request(request)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/kavimuthurajas/PycharmProjects/Amber-OPCGateway/venv/lib/python3.11/site-packages/asyncua/client/ua_client.py", line 170, in send_request
    raise ConnectionError("Connection is closed") from None
ConnectionError: Connection is closed

解决思路

  • 修复连接逻辑冲突
    async with Client上下文管理器会自动完成连接和资源释放,手动调用await client.connect()会导致重复创建安全通道,引发ID无效错误。修改后的代码:

    import asyncio
    from asyncua import Client
    
    async def read_opcua_node(endpoint_url, node_id):
        async with Client(url=endpoint_url) as client:
            # 移除手动connect调用,上下文管理器已自动处理连接
            node = await client.get_node(node_id)
            value = await node.read_value()
            print(f"Value of node {node_id}: {value}")
    
    if __name__ == "__main__":
        endpoint_url = "opc.tcp://172.10.0.13:4840"
        node_id = "ns=2;i=0"
        asyncio.run(read_opcua_node(endpoint_url, node_id))
    
  • 匹配会话超时设置
    日志显示服务器将请求的3600000ms超时调整为60000ms,可手动设置客户端超时匹配服务器限制:

    async with Client(url=endpoint_url) as client:
        client.set_session_timeout(60000)
        # 后续操作...
    
  • 检查服务器与网络状态

    • 确认OPC UA服务器正常运行,端点opc.tcp://172.10.0.13:4840可通过telnet/nc命令测试连通性
    • 排查防火墙、NAT规则是否拦截了4840端口的通信
    • 若服务器启用安全验证,客户端需匹配对应的安全模式(如None、Sign)和安全策略(如Basic256Sha256)
  • 更新AsyncUA库
    旧版本库可能存在安全通道管理bug,执行pip install --upgrade asyncua更新到最新稳定版

内容的提问来源于stack exchange,提问作者KAVI MUTHU RAJA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:08:11