Reputation: 651
I am using pysnmp to get a list of IP and mac address from ipNetToMediaPhysAddress This is working with no issue. I have a problem however converting the mac address to human readable one. the SNMP code has caused the mac to appear as
0x05056bdafc
I am wondering how to convert this to a human readable mac address. I understand that some 0's are missing as per details here - http://blog.colovirt.com/2009/05/05/linuxnetworkingvmware-snmpwalk-mac-address-missing-0s/
Is there some code or a way using pysnmp to covert it to human readable?
Cheers for your help
Upvotes: 0
Views: 1831
Reputation: 5555
The SNMP way would be to use MIB(s) to resolve all received values into human-friendly form. The lookupValues=True flag in this example does the trick. However you would first have to: A) convert your conventional MIB and all other MIBs it depends on into pysnmp format and B) load your pysnmp-MIBs to your pysnmp-based app (through MibVariable.loadMibs()).
Alternatively, if you know exact OIDs whose value is a MAC, then the following piece of code may help:
>>> from pysnmp.smi import builder
>>> mibBuilder = builder.MibBuilder()
>>> MacAddress, = mibBuilder.importSymbols('SNMPv2-TC', 'MacAddress')
>>> macAddress = MacAddress(hexValue='05056bdafc'.zfill(12))
>>> macAddress.prettyPrint()
'00:05:05:6b:da:fc'
Or it could probably be done just in Python:
>>> mac = '05056bdafc'.zfill(12)
>>> ':'.join([ mac[i:i+2] for i in range(0, 12, 2) ])
'00:05:05:6b:da:fc'
Upvotes: 1
Reputation: 4796
You can use the netaddr
package. If you're working on Ubuntu/Debian you can easily install it this way:
# apt-get install python-netaddr
Alternatively you can install it with pip
in a virtualenv or Python3 venv:
$ source myenvironment/bin/activate
$ pip install netaddr
Then you can try this:
$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from netaddr import *
>>> mac = EUI(0x05056bdafc)
>>>
>>> print mac
00-05-05-6B-DA-FC
>>>
or with Python 3:
$ python
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from netaddr import *
>>>
>>>
>>> mac = EUI(0x05056bdafc)
>>>
>>> print (mac)
00-05-05-6B-DA-FC
>>>
>>> mac.dialect = mac_unix
>>>
>>> print (mac)
0:5:5:6b:da:fc
You can find more examples here.
Hope this helps. Good luck!
Upvotes: 2