charlestolley / python-snmp

A user-friendly SNMP library
MIT License
16 stars 3 forks source link

Garbled hex-string #7

Closed KkristJ closed 10 months ago

KkristJ commented 10 months ago

Hi, using snmp 0.7.1 on vscode on windows 11 I get garbled hex-string occasionally/always... I compare to linux snmpwalk. I read switches, mainly HP, and most snmp data is correct, but MAC adresses and longer hex strings are shortened and garbled. I do

    response = localhost.get(oid)
    var = response.variables[0].value.data

and expect for instance '00:0a:cd:42:2f:24', but get b'\x00\n\xcdA/#'. Is there i fix for this? Thanks

charlestolley commented 10 months ago

What you are describing is not a bug. A MAC address is 6 bytes long, so b'\x00\n\xcdA/#' is perfectly valid. If you use a tool like snmpget, it will print it in the "00:0a:cd:41:2f:23" format that you are expecting, but this library operates at a slightly lower level than the netsnmp command-line tools.

This formatting is very simple to implement. Here's an example, which I ran in the Python interpreter shell:

>>> def format_mac(addr):
...     return ":".join((f"{byte:02x}" for byte in addr))
... 
>>> format_mac(b'\x00\n\xcdA/#')
'00:0a:cd:41:2f:23'
KkristJ commented 10 months ago

Thank you, Charles

lextm commented 2 weeks ago

@KkristJ Deep down inside, the correct formatting of output relies on the metadata provided by MIB documents, so that we know the exact type of each objects.

In your case, the OID might be of PhysAddress or an equivalent type, that its data should be formatted as HEX strings, instead of ASCII/Unicode strings.

So overall an SNMP library like this might gain more capabilities if MIB support is added. Net-SNMP (the snmpwalk utility you use) already includes that, as well as other SNMP libraries.