pyroute2: Python Netlink library

0.9.5 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

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`.

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}")

view raw JSON →