Skip to content

Instantly share code, notes, and snippets.

@grafuls
Last active February 5, 2021 14:29
Show Gist options
  • Save grafuls/103dd7900aa3fbb72b0bf69527033bce to your computer and use it in GitHub Desktop.
Save grafuls/103dd7900aa3fbb72b0bf69527033bce to your computer and use it in GitHub Desktop.
python snmp getter with parser for mac address and ip
#! /usr/bin/env python
from pysnmp import hlapi
from pysnmp.smi import builder
from pyasn1.type.univ import OctetString
from pysnmp.proto.rfc1902 import OctetString, IpAddress
def get(target, oids, credentials, port, engine, context):
udp_target = hlapi.UdpTransportTarget((target, port))
object_types = construct_object_types(oids)
handler = hlapi.getCmd(engine, credentials, udp_target, context, *object_types)
return fetch(handler, 1)[0]
def construct_object_types(list_of_oids):
object_types = []
for oid in list_of_oids:
object_types.append(hlapi.ObjectType(hlapi.ObjectIdentity(oid)))
return object_types
def cast(value):
if type(value) == OctetString:
mibBuilder = builder.MibBuilder()
MacAddress, = mibBuilder.importSymbols('SNMPv2-TC', 'MacAddress')
hex_value = ''.join(['%.2x' % x for x in value.asOctets()])
macAddress = MacAddress(hexValue=hex_value.zfill(12))
return macAddress.prettyPrint()
if type(value) == IpAddress:
ip = '.'.join(['%d' % x for x in value.asNumbers()])
return ip
try:
return int(value)
except (ValueError, TypeError):
try:
return float(value)
except (ValueError, TypeError):
try:
return str(value)
except (ValueError, TypeError):
pass
return value
def fetch(handler, count):
result = []
for i in range(count):
try:
error_indication, error_status, error_index, var_binds = next(handler)
if not error_indication and not error_status:
items = {}
for var_bind in var_binds:
items[str(var_bind[0])] = cast(var_bind[1])
result.append(items)
else:
raise RuntimeError('Got SNMP error: {0}'.format(error_indication))
except StopIteration:
break
return result
if __name__ == "__main__":
target = "10.1.44.70"
oids = [
'1.3.6.1.2.1.4.22.1.2.6.10.1.45.254',
'1.3.6.1.2.1.4.22.1.1.6.10.1.45.254',
'1.3.6.1.2.1.2.2.1.5.6',
'1.3.6.1.2.1.3.1.1.2.6.1.10.1.45.254',
'1.3.6.1.2.1.4.20.1.1.10.1.44.70',
]
credentials = hlapi.CommunityData('public')
port = 161
engine=hlapi.SnmpEngine()
context=hlapi.ContextData()
print(get(target, oids, credentials, port, engine, context))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment