{"id":2713,"library":"pyroute2","title":"pyroute2: Python Netlink library","description":"pyroute2 is a pure Python library for Linux network management using the Netlink socket API. It provides a programmatic interface to the same functionality as `iproute2` utilities, supporting various Netlink protocols like RTNL (IP settings, routing), WireGuard, nftables, nl80211 (WiFi), and more. Starting from version 0.9.1, its core has been rewritten to be `asyncio`-based, with synchronous APIs implemented as wrappers for compatibility. The current version is 0.9.5, with an active release cadence.","status":"active","version":"0.9.5","language":"en","source_language":"en","source_url":"https://github.com/svinota/pyroute2","tags":["networking","linux","netlink","asyncio","routing","network-namespaces"],"install":[{"cmd":"pip install pyroute2","lang":"bash","label":"Install stable version"}],"dependencies":[],"imports":[{"note":"Synchronous RTNL (routing) API, implemented as a wrapper around the asyncio core.","symbol":"IPRoute","correct":"from pyroute2 import IPRoute"},{"note":"Asynchronous RTNL (routing) API, the primary interface since v0.9.1.","symbol":"AsyncIPRoute","correct":"from pyroute2 import AsyncIPRoute"},{"note":"High-level, transactional API for network settings, designed to replace IPDB.","symbol":"NDB","correct":"from pyroute2 import NDB"},{"note":"Legacy class for network namespace management; in newer versions, use `netns` argument directly with `IPRoute` or `AsyncIPRoute`.","symbol":"NetNS","correct":"from pyroute2 import NetNS"},{"note":"IPDB is officially deprecated since v0.7.12 and removed from the library in recent versions, serving only as a minimal compatibility wrapper around NDB. It should not be used for new projects.","wrong":"from pyroute2 import IPDB","symbol":"IPDB","correct":"from pyroute2 import IPDB"}],"quickstart":{"code":"import os\nfrom pyroute2 import IPRoute\n\n# Note: pyroute2 operations often require root privileges.\n# It's highly recommended to run this script with 'sudo python your_script.py'\n# or ensure the user has CAP_NET_ADMIN capability.\n# For a non-root setup (e.g., remote access), consider RemoteIPRoute with mitogen.\n\n# Synchronous example: List network interfaces\ntry:\n    with IPRoute() as ipr:\n        # Get all link (interface) objects\n        links = ipr.get_links()\n\n        print(\"\\nNetwork Interfaces:\")\n        for link in links:\n            # Access attributes using .get_attr() or dictionary-like access\n            ifname = link.get_attr('IFLA_IFNAME')\n            state = link.get_attr('IFLA_OPERSTATE') or 'UNKNOWN'\n            address = link.get_attr('IFLA_ADDRESS') or 'N/A'\n            index = link['index']\n            print(f\"  Index: {index}, Name: {ifname}, State: {state}, MAC: {address}\")\n\n    # Asynchronous example (requires `await` in an async function):\n    # import asyncio\n    # from pyroute2 import AsyncIPRoute\n    # async def async_main():\n    #     async with AsyncIPRoute() as ipr:\n    #         print(\"\\nAsync Network Interfaces:\")\n    #         async for link in await ipr.link(\"dump\"):\n    #             ifname = link.get(\"ifname\")\n    #             state = link.get(\"state\")\n    #             address = link.get(\"address\")\n    #             print(f\"  Name: {ifname}, State: {state}, MAC: {address}\")\n    # asyncio.run(async_main())\n\nexcept PermissionError:\n    print(\"\\nPermission denied. Most pyroute2 operations require root privileges (e.g., run with 'sudo').\")\nexcept Exception as e:\n    print(f\"\\nAn error occurred: {e}\")\n","lang":"python","description":"This quickstart demonstrates how to use the synchronous `IPRoute` API to list network interfaces on a Linux system. It's crucial to note that `pyroute2` operations typically require root privileges or `CAP_NET_ADMIN` capabilities. The example includes comments on how to adapt for asynchronous usage with `AsyncIPRoute`."},"warnings":[{"fix":"For new development, prioritize using `AsyncIPRoute` and `await`able methods within `async` functions. For existing synchronous code, ensure you use the `IPRoute` context manager (`with IPRoute() as ipr:`) and adapt to its API, noting that some low-level socket interactions might need refactoring.","message":"The core of pyroute2 was entirely rewritten to be `asyncio`-based in version 0.9.1. While a synchronous API (`IPRoute`) is provided for compatibility, it's now a wrapper around the asynchronous core. Direct low-level socket operations (`recv()`, `sendmsg()`) are no longer directly supported on socket objects controlled by the asyncio event loop.","severity":"breaking","affected_versions":">=0.9.1"},{"fix":"Migrate from `IPDB` to the `NDB` (Netlink Database) module, which offers a robust, high-level API with a different architecture.","message":"The `IPDB` module, a high-level transactional database for network settings, has been deprecated since v0.7.12 and largely removed, serving only as a compatibility wrapper for `NDB`. It is explicitly advised *not* to use `IPDB` for new projects.","severity":"deprecated","affected_versions":">=0.7.12 (deprecated), >=0.9.0 (effectively removed/wrapper)"},{"fix":"If you were using the `NDB` CLI, you will need to replace its functionality with equivalent Python API calls using the `pyroute2.NDB` module.","message":"The `NDB` (Netlink Database) CLI (Command Line Interface) was deprecated and removed in version 0.9.3rc1. The `NDB` Python API itself remains active and is the recommended high-level interface.","severity":"deprecated","affected_versions":">=0.9.3rc1"},{"fix":"Execute your Python script with `sudo` (e.g., `sudo python your_script.py`) or ensure the user executing the script has the necessary Linux capabilities.","message":"Most operations performed by `pyroute2` (e.g., modifying network interfaces, routes, addresses) require root privileges (`sudo`) or the `CAP_NET_ADMIN` capability. Running scripts without these permissions will result in `PermissionError` or similar failures.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always use `IPRoute` (and similar classes) as a context manager (`with IPRoute() as ipr:`) to ensure sockets are properly closed, even if errors occur.","message":"For synchronous `IPRoute` or other socket-based objects, it's crucial to explicitly release resources and close sockets to prevent resource leaks. While Python's garbage collection will eventually close file descriptors, explicit closure is best practice.","severity":"gotcha","affected_versions":"All versions"},{"fix":"In multithreaded applications that create network namespaces, set `pyroute2.config.child_process_mode = 'mp'` (for `multiprocessing.Process()`) for a safer, albeit potentially slower, operation. `from pyroute2.config import setup; setup.child_process_mode = 'mp'`","message":"When managing network namespaces in multithreaded applications, `pyroute2.config.child_process_mode` defaults to 'fork', which is not thread-safe and can lead to warnings.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-10T00:00:00.000Z","next_check":"2026-07-09T00:00:00.000Z"}