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

Python使用opcua库连接Basic256Sha256无证书Opc Ua服务器问题求助

解决方案

问题根因

OPC UA规范中Basic256Sha256安全策略的Sign签名模式本身需要非对称密钥对完成签名运算,厂商提到的「不使用任何证书」实际是指无需提前准备CA签发的正式证书、无需校验服务器证书,并非完全跳过证书环节。你使用的freeopcua(即opcua包)支持在内存中自动生成临时自签名证书,无需本地存储证书文件,完全符合需求。

实现代码

方案1:显式生成临时证书(兼容性最好)

from opcua import Client
from opcua import ua
from opcua.crypto import uacrypto

# 替换为你的OPC UA服务器地址
url = "opc.tcp://<服务器IP>:<端口>/<资源路径>"
client = Client(url)

# 内存生成临时自签名证书和私钥,不会写入本地磁盘
cert, priv_key = uacrypto.generate_self_signed_certificate(
    application_uri=client.application_uri,
    days=365,
    output_format="DER"
)

# 配置安全策略,关闭服务器证书校验
client.set_security(
    policy=ua.SecurityPolicyType.Basic256Sha256_Sign,
    certificate=cert,
    private_key=priv_key,
    server_certificate=None
)

# 连接测试
try:
    client.connect()
    print("连接服务器成功")
    # 此处编写业务逻辑代码
finally:
    client.disconnect()

方案2:简化配置(适合新版本opcua库)

直接在安全字符串中留空证书参数,库会自动生成临时证书:

from opcua import Client

url = "opc.tcp://<服务器IP>:<端口>/<资源路径>"
client = Client(url)

# 直接配置安全字符串,自动生成临时证书、跳过服务器证书校验
client.set_security_string("Basic256Sha256,Sign,,")

try:
    client.connect()
    print("连接服务器成功")
    # 业务逻辑
finally:
    client.disconnect()

注意事项

  • 如果运行报错,先升级opcua库到最新版本:pip install --upgrade opcua
  • 若仍连接失败,确认服务器端已开启「允许客户端自签名证书」、「关闭客户端证书校验」的相关配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:06:08