[Python] OPC UA Python Client Connection Fails with "BadSecurityPolicyRejected" Despite Using...

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    Connecting to opc.tcp://172.16.0.1:4844...

    C:\Users\Administrator\PycharmProjects\PythonProject1\intro.py:272: RuntimeWarning: coroutine 'Client.set_security_string' was never awaited

    client.set_security_string(f"Basic256Sha256,SignAndEncrypt,{cert_path},{key_path}")

    RuntimeWarning: Enable tracemalloc to get the object allocation traceback ServiceFault (BadSecurityPolicyRejected, diagnostics: DiagnosticInfo(SymbolicId=None, NamespaceURI=None, Locale=0, LocalizedText=None, AdditionalInfo=None, InnerStatusCode=None, InnerDiagnosticInfo=None))

    from server received in response to CreateSessionRequest Error: The security policy does not meet the requirements set by the server.(BadSecurityPolicyRejected)

    Updated status of server ID None to 'Not Running'. Inserted action log for Server ID None: Not Running in 172.16.0.1


    for server in servers:
    endpoint_url = server.EndpointUrl
    server_ip = server.ServerIP
    print(f"Connecting to {endpoint_url}...")

    if not ping_server(server_ip):
    print(f"{server_ip} is not reachable.")
    update_server_status(cursor, None, "Not Running", server_ip)
    continue

    try:
    # Configure OPC UA client
    client = Client(endpoint_url)
    client.set_user("DEWA_OPC")
    client.set_password("RTeK8QrF9F5G")
    client.set_security_string(f"Basic256Sha256,SignAndEncrypt,{cert_path},{key_path}")
    await client.connect() # Await the connection
    print(f"Connected to OPC UA server at {endpoint_url}")

    update_server_status(cursor, None, "Running", server_ip)

    cursor.execute("SELECT [TagName] FROM [admin_db].[dbo].[opc_ua_tag_name]")
    tag_names = [row.TagName for row in cursor.fetchall()]

    root = client.get_root_node()
    historical_data_node = client.get_node("ns=2;s=RealTimeData") # Adjust the node as needed

    # Continuously fetch real-time data for each tag
    for tag_name in tag_names:
    await fetch_and_insert_data(tag_name, historical_data_node)

    await client.disconnect() # Await disconnection
    print("Real-time data fetch cycle completed.")

    except Exception as e:
    print(f"Error: {e}")
    update_server_status(cursor, None, "Not Running", server_ip)

    await asyncio.sleep(10) # Wait for 10 seconds before the next cycle

    except Exception as e:
    print(f"Error in main loop: {e}")


    I'm trying to connect to an OPC UA server at opc.tcp://172.16.0.1:4844 using Python and the asyncua library. I want to use a secure connection with the Basic256Sha256 security policy and client certificate authentication.
    When I run this, I get the following warning and error that mentioned above.


    1. Verified that the server supports Basic256Sha256.


    2. Confirmed that cert_path and key_path point to valid files.


    3. Looked up the error and suspect I may be misusing set_security_string.

      How should I correctly use set_security_string() with asyncua in an async context? And what could be causing the BadSecurityPolicyRejected error?

    Continue reading...

Compartilhe esta Página