Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python parser for unix "ip address" command (iproute2)

short version:

is there a library to parse the output of the unix command:

ip address

If the answer is no, do you know any python networking library that I could use to speed up the development of a parser?

Detailed explanation:

I'm trying to build an open source abstraction layer to retrieve information from network devices with different protocols (SSH, SNMP, HTTP) to be used in wireless community networks, I started from SSH (prototype here) and initially I found a parser for the "ifconfig" command, but the parser does not take into account many cases plus my networking friends told me the "ifconfig" has been deprecated and "iproute2" is the future.

So, before start to develop my own, I ask if anybody knows if there is any open source python parser for the output of the "ip address" unix command. I just need to retrieve a list of interfaces, each interface being a dictionary or an object, with all the details contained in the output of the command (name, type, ip, mac, mtu, ecc).

The only thing I've found is this undocumented and unfinished github repo: https://github.com/nwhalen/python-iproute2

like image 1000
nemesisdesign Avatar asked Aug 11 '26 09:08

nemesisdesign


2 Answers

You can use the python pyroute2 library:

from pyroute2 import IPRoute
ip = IPRoute()
ip.get_addr(label='eth0')[0].get_attr('IFA_ADDRESS')

For more information you can check here: http://pyroute2.org/pyroute2-0.3.14p4/iproute.html

like image 154
belabrinel Avatar answered Aug 13 '26 00:08

belabrinel


Please just use the python netifaces library.

pip install netifaces

Usage

>>>import netifaces
>>>netifaces.interfaces()
['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']
>>>netifaces.ifaddresses('lo0')
{18: [{'addr': ''}], 2: [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}], 30: [{'peer': '::1', 'netmask': 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', 'addr': '::1'}, {'peer': '', 'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::1%lo0'}]}
like image 32
han solo Avatar answered Aug 13 '26 00:08

han solo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!