pyroute2: Python Netlink library
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.
Warnings
- breaking 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.
- deprecated 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.
- deprecated 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.
- gotcha 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.
- gotcha 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.
- gotcha 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.
Install
-
pip install pyroute2
Imports
- IPRoute
from pyroute2 import IPRoute
- AsyncIPRoute
from pyroute2 import AsyncIPRoute
- NDB
from pyroute2 import NDB
- NetNS
from pyroute2 import NetNS
- IPDB
from pyroute2 import IPDB
Quickstart
import os
from pyroute2 import IPRoute
# Note: pyroute2 operations often require root privileges.
# It's highly recommended to run this script with 'sudo python your_script.py'
# or ensure the user has CAP_NET_ADMIN capability.
# For a non-root setup (e.g., remote access), consider RemoteIPRoute with mitogen.
# Synchronous example: List network interfaces
try:
with IPRoute() as ipr:
# Get all link (interface) objects
links = ipr.get_links()
print("\nNetwork Interfaces:")
for link in links:
# Access attributes using .get_attr() or dictionary-like access
ifname = link.get_attr('IFLA_IFNAME')
state = link.get_attr('IFLA_OPERSTATE') or 'UNKNOWN'
address = link.get_attr('IFLA_ADDRESS') or 'N/A'
index = link['index']
print(f" Index: {index}, Name: {ifname}, State: {state}, MAC: {address}")
# Asynchronous example (requires `await` in an async function):
# import asyncio
# from pyroute2 import AsyncIPRoute
# async def async_main():
# async with AsyncIPRoute() as ipr:
# print("\nAsync Network Interfaces:")
# async for link in await ipr.link("dump"):
# ifname = link.get("ifname")
# state = link.get("state")
# address = link.get("address")
# print(f" Name: {ifname}, State: {state}, MAC: {address}")
# asyncio.run(async_main())
except PermissionError:
print("\nPermission denied. Most pyroute2 operations require root privileges (e.g., run with 'sudo').")
except Exception as e:
print(f"\nAn error occurred: {e}")