-1

I'm creating a SNMP program to list interfaces (with ip, mask and mac) of devices. I'm using NetSnmp to get the macaddress but the output looks like this ('\x00PV\xaf\x00v',)

This is the SNMP request:

    oidmac = netsnmp.Varbind("ifPhysAddress."+i)

    mac = netsnmp.snmpget(
        oidmac, 
        Version = 2, 
        DestHost = sys.argv[2], 
        Community = sys.argv[1])

Info about the code ...

  • sys.argv[1] = Community string
  • sys.argv[2] = IP of the SNMP agent
  • i = a variable with the interface ID.

How can I convert the string to an MAC address in format aa:bb:cc:dd:11:22 ?

k1eran
  • 4,492
  • 8
  • 50
  • 73

1 Answers1

0

In Python2, it's very simple

>>> ":".join(x.encode('hex') for x in '\x00PV\xaf\x00v')
'00:50:56:af:00:76'

For Python3, you can try something like this

>>> "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*b'\x00PV\xaf\x00v')
'00:50:56:af:00:76'

Use :02X (capital X) if you want uppercase hex codes

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • Hellp John! I first triyed your code in ipython for (im using python2) wihich worked! I then added this to my code: mac2 = ":".join(x.encode('hex') for x in mac) I get a error tho, which is: Traceback (most recent call last): File "./program.py", line 37, in mac2 = ":".join(x.encode('hex') for x in mac) File "./program.py", line 37, in mac2 = ":".join(x.encode('hex') for x in mac) AttributeError: 'NoneType' object has no attribute 'encode' – Jacob Åkerblom Mar 13 '15 at 12:47
  • @JacobÅkerblom, a string can't have `None` when you iterate over it. Check what type `mac` is – John La Rooy Mar 13 '15 at 22:14
  • My variable mac is a tuple according to print type(mac). – Jacob Åkerblom Mar 14 '15 at 11:30