我正在使用PySNMP来获取CDP邻居的IP。
这是我当前的函数,它可以工作,但输出的类型为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)
输出以下内容:
[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
如何将0xac14103a
转换为IP地址?
或者是否有可能以某种方式获取CiscoNetworkAddress
?
答案 0 :(得分:2)
根据CISCO-TC
MIB,您必须手动解释地址值,并考虑cacheAddressType
列指定的地址类型:
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
如果是IPv4值,您可以手动将该八位字节串转换为IPv4地址:
# 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'
或使用ipaddress
stdlib模块:
>>> ipaddress.IPv4Address(value.asOctets())
IPv4Address('172.20.16.58')