Python · recipe
Connect to an OPC UA server in Python
Use asyncua's Client as an async context manager. The context manager opens the secure channel and session on entry and closes both on exit, which is the part hand-rolled code usually gets wrong. This connects with no security, which is the correct first diagnostic step.
| Stack | asyncua (FreeOpcUa/opcua-asyncio) |
|---|---|
| Version | 2.0.1 |
The code
import asyncio
from asyncua import Client
URL = "opc.tcp://opcua.umati.app:4840"
async def main():
async with Client(url=URL) as client:
print("connected to", URL)
print("namespaces:")
for i, uri in enumerate(await client.get_namespace_array()):
print(f" ns={i} {uri}")
asyncio.run(main())
What it prints
connected to opc.tcp://opcua.umati.app:4840
namespaces:
ns=0 http://opcfoundation.org/UA/
ns=1 urn:umati:sample-server
ns=2 http://opcfoundation.org/UA/DI/
ns=3 http://opcfoundation.org/UA/Machinery/
ns=4 http://opcfoundation.org/UA/MachineTool/
Notes
- Print the namespace array on every first connection. It tells you which companion specifications the server implements before you browse anything, and you need the URI-to-index mapping anyway.
- Connect with security None first even on a server you intend to secure. If None works and SignAndEncrypt does not, the problem is certificates, and you have just halved your search space.
- For scripts and notebooks, `from asyncua.sync import Client` gives the same API without asyncio.
What breaks first
The server rejects your certificate the first time you try a secure connection
Your certificate lands in the server's rejected store. Move it to the trusted store on the server, and trust the server's certificate on your side too: both directions are required.
BadCertificateUntrustedYour certificate lands in the server's rejected store. Move it to the trusted store on the server, and trust the server's certificate on your side too: both directions are required.
Other recipes in this stack
Concepts on this page
Last verified 7 September 2026 against OPC UA 1.05.07. OPC UA Connect is an educational resource and is not affiliated with the OPC Foundation.