Package: pyroute2
Pyroute2 is a pure Pythonnetlinklibrary. The core requires only Python
stdlib, no 3rd party libraries. The library was started as an RTNL protocol
implementation, so the name ispyroute2, but now it supports many netlink
protocols. Some supported netlink families and protocols:rtnl, network settings — addresses, routes, traffic controlsnfnetlink— netfilter APIipq— simplest userspace packet filtering, iptables QUEUE targetdevlink— manage and monitor devlink-enabled hardwaregeneric— generic netlink familiesuevent— same uevent messages as in udevNetfilter API:ipset— IP setsnftables— packet filteringnfct— connection trackingGeneric netlink:ethtool— low-level network interface setupwireguard— VPN setupnl80211— wireless functions API (basic support)taskstats— extended process statisticsacpi_events— ACPI events monitoringthermal_events— thermal events monitoringVFS_DQUOT— disk quota events monitoringOn the low level the library provides socket objects with an
extended API. The additional functionality aims to:Help to open/bind netlink socketsDiscover generic netlink protocols and multicast groupsConstruct, encode and decode netlink and PF_ROUTE messagesSupported systemsPyroute2 runs natively on Linux and emulates some limited subset
of RTNL netlink API on BSD systems on top of PF_ROUTE notifications
and standard system tools.Other platforms are not supported.NDB – high level RTNL APIKey features:Data integrityTransactions with commit/rollback changesState synchronizationMultiple sources, including netns and remote systemsA “Hello world” example:frompyroute2importNDBwithNDB()asndb:withndb.interfaces['eth0']aseth0:# set one parametereth0.set(state='down')eth0.commit()# make sure that the interface is down# or multiple parameters at onceeth0.set(ifname='hello_world!',state='up')eth0.commit()# rename, bring up and wait for success# --> <-- here you can be sure that the interface is up & renamedMore examples:frompyroute2importNDBndb=NDB(log='debug')forrecordinndb.interfaces.summary():print(record.ifname,record.address,record.state)if_dump=ndb.interfaces.dump()if_dump.select_records(state='up')if_dump.select_fields('index','ifname','kind')forlineinif_dump.format('json'):print(line)addr_summary=ndb.addresses.summary()addr_summary.select_records(ifname='eth0')forlineinaddr_summary.format('csv'):print(line)withndb.interfaces.create(ifname='br0',kind='bridge')asbr0:br0.add_port('eth0')br0.add_port('eth1')br0.add_ip('10.0.0.1/24')br0.add_ip('192.168.0.1/24')br0.set(br_stp_state=1,# set STP onbr_group_fwd_mask=0x4000,# set LLDP forwardingstate='up',# bring the interface up)# --> <-- commit() will be run by the context manager# operate on netns:ndb.sources.add(netns='testns')# connect to a namespacewith(ndb.interfaces.create(ifname='veth0',# create vethkind='veth',peer={'ifname':'eth0',# setup peer'net_ns_fd':'testns',# in a namespace},state='up',))asveth0:veth0.add_ip(address='172.16.230.1',prefixlen=24)withndb.interfaces.wait(target='testns',ifname='eth0')aspeer:# wait for the peerpeer.set(state='up')# bring it uppeer.add_ip('172.16.230.2/24')# add addressIPRoute – Low level RTNL APILow-levelIPRouteutility — Linux network configuration.
TheIPRouteclass is a 1-to-1 RTNL mapping. There are no implicit
interface lookups and so on.Get notifications about network settings changes with IPRoute:frompyroute2importIPRoutewithIPRoute()asipr:# With IPRoute objects you have to call bind() manuallyipr.bind()formessageinipr.get():print(message)More examples:fromsocketimportAF_INETfrompyroute2importIPRoute# get access to the netlink socketipr=IPRoute()# no monitoring here -- thus no bind()# print interfacesforlinkinipr.get_links():print(link)# create VETH pair and move v0p1 to netns 'test'ipr.link('add',ifname='v0p0',peer='v0p1',kind='veth')# wait for the devices:peer,veth=ipr.poll(ipr.link,'dump',timeout=5,ifname=lambdax:xin('v0p0','v0p1'))ipr.link('set',index=peer['index'],net_ns_fd='test')# bring v0p0 up and add an addressipr.link('set',index=veth['index'],state='up')ipr.addr('add',index=veth['index'],address='10.0.0.1',prefixlen=24)# release Netlink socketip.close()Network namespace examplesNetwork namespace manipulation:frompyroute2importnetns# create netnsnetns.create('test')# listprint(netns.listnetns())# remove netnsnetns.remove('test')Createvethinterfaces pair and move tonetns:frompyroute2importIPRoutewithIPRoute()asipr:# create interface pairipr.link('add',ifname='v0p0',kind='veth',peer='v0p1')# wait for the peer(peer,)=ipr.poll(ipr.link,'dump',timeout=5,ifname='v0p1')# move the peer to the 'test' netns:ipr.link('set',index=peer['index'],net_ns_fd='test')List interfaces in somenetns:frompyroute2importNetNSfrompprintimportpprintns=NetNS('test')pprint(ns.get_links())ns.close()More details and samples see in the documentation.InstallationUsing pypi:pipinstallpyroute2Using git:pipinstallgit+https://github.com/svinota/pyroute2.gitUsing source, requires make and noxgitclonehttps://github.com/svinota/pyroute2.gitcdpyroute2makeinstallRequirementsPython >= 3.6Linkshome:https://pyroute2.org/source:https://github.com/svinota/pyroute2bugs:https://github.com/svinota/pyroute2/issuespypi:https://pypi.python.org/pypi/pyroute2docs:http://docs.pyroute2.org/