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

Python连接带账号密码的OPC UA服务器遇端点错误及key.pem查找问题

解决OPC UA Python客户端连接错误及证书密钥查找问题

一、先排查端点不匹配核心问题

错误提示的本质是客户端请求的安全策略/模式与服务器提供的端点不兼容。你可以先通过无安全连接(若服务器允许)获取服务器实际支持的端点信息,明确正确的安全配置:

from opcua import Client

client = Client("opc.tcp://<ip>:4840")
# 临时注释安全相关配置,优先获取端点列表
try:
    client.connect()
    endpoints = client.get_server_endpoints()
    for ep in endpoints:
        print(f"端点URL: {ep.EndpointUrl}")
        print(f"安全模式: {ep.SecurityMode}")
        print(f"安全策略URI: {ep.SecurityPolicyUri}")
        print("---")
finally:
    client.disconnect()

运行后就能看到服务器支持的安全组合,比如是否真的兼容Basic256Sha256+Sign模式,避免用错配置。

二、定位UAExpert的密钥文件(key.pem)

UAExpert的证书和密钥存储路径随系统不同而变化:

Windows系统

默认路径:C:\Users\<你的用户名>\AppData\Roaming\UnifiedAutomation\UaExpert\pki\own\private
密钥文件通常命名为private_key.pem,或与证书同名(比如证书是cert.der,密钥可能是cert_key.pem)

Linux/macOS系统

默认路径:~/.config/UnifiedAutomation/UaExpert/pki/own/private
查找.pem格式的私有密钥文件即可

找到后,将密钥的完整路径填入代码的安全字符串中,示例:

client.set_security_string("Basic256Sha256,Sign,C:/Users/xxx/AppData/Roaming/UnifiedAutomation/UaExpert/pki/own/cert.der,C:/Users/xxx/AppData/Roaming/UnifiedAutomation/UaExpert/pki/own/private/private_key.pem")

三、额外排查要点

  • 证书信任问题:服务器可能需要将客户端证书加入信任列表,把UAExpert的cert.der导入服务器信任证书库(和UAExpert连接时的操作一致)。
  • 安全模式严格匹配:确保set_security_string中的安全模式(Sign/SignAndEncrypt)与服务器端点的安全模式完全一致,比如服务器只支持SignAndEncrypt时,用Sign会报错。
  • 代码顺序调整:部分服务器要求先设置安全配置,再设置用户名密码,调整顺序尝试:
client = Client("opc.tcp://<ip>:4840")
client.set_security_string("Basic256Sha256,Sign,cert_path,key_path")
client.set_user("username")
client.set_password("password")
client.connect()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:22:50