ChaChaPoly
ChaChaPoly

Reputation: 1851

PySNMP hexValue to IP

I am using PySNMP to get the IPs of the CDP neighbors. This is my current function, which works, but the output is of the type hexValue.

def get_neighbors():
    for (errorIndication,
         errorStatus,
         errorIndex,
         values) in nextCmd(SnmpEngine(),
                            CommunityData('public', mpModel=0),
                            UdpTransportTarget((SWITCH, 161)),
                            ContextData(),
                            ObjectType(ObjectIdentity('CISCO-CDP-MIB', 'cdpCacheAddress')).addAsn1MibSource('file://asn1/CISCO-CDP-MIB'),
                            lexicographicMode=False, lookupNames=True, lookupValues=True):
        print(values)
        for v in values:
            print(v)

It outputs the following:

[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.4.1.9.9.23.1.2.1.1.4.10106.14')), CiscoNetworkAddress(hexValue='ac14103a'))]
CISCO-CDP-MIB::cdpCacheAddress.10106.14 = 0xac14103a
[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.4.1.9.9.23.1.2.1.1.4.10125.9')), CiscoNetworkAddress(hexValue='ac1413fc'))]
CISCO-CDP-MIB::cdpCacheAddress.10125.9 = 0xac1413fc

How can I convert 0xac14103a to an IP address? Or is ist possible to somehow fetch the value of CiscoNetworkAddress?

Upvotes: 0

Views: 1268

Answers (1)

Ilya Etingof
Ilya Etingof

Reputation: 5555

According to CISCO-TC MIB, you have to interpret the address value by hand taking into account the type of the address as specified by cacheAddressType column:

CiscoNetworkAddress ::= TEXTUAL-CONVENTION
    DESCRIPTION
        "Represents a network layer address.  The length and format of
        the address is protocol dependent as follows:
        ip        4 octets
        ...
        ipv6      16 octets
        ...
        http     up to 70 octets
SYNTAX          OCTET STRING

If it is an IPv4 value, you can convert that octet-string into IPv4 address by hand:

# unpacking your `v` loop variable which is a tuple of SNMP var-bindings
# both `oid` and `value` are pysnmp objects representing SNMP types...
>>> oid, value = v
>>> '.'.join([str(x) for x in value.asNumbers()])
'172.20.16.58'

Or with ipaddress stdlib module:

>>> ipaddress.IPv4Address(value.asOctets())
IPv4Address('172.20.16.58')

Upvotes: 2

Related Questions