from pysnmp.hlapi import * import os,sys
class NetSNMP(): def __init__(self,address,region): self.region = region self.address = address
def GetNumber(self,oid,sub_oid,sub_id): iterator = getCmd(SnmpEngine(), CommunityData(self.region), UdpTransportTarget((self.address, 161)), ContextData(), ObjectType(ObjectIdentity(oid, sub_oid, sub_id))) errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
if errorIndication: return False else: if errorStatus: return False else: for varBind in varBinds: return [x.prettyPrint() for x in varBind]
def WalkNumber(self, oid): res = [] for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData(self.region),UdpTransportTarget((self.address, 161)),ContextData(), ObjectType(ObjectIdentity(oid)).addMibSource( './site-packages/pysnmp/smi/mibs','pysnmp_mibs'),lexicographicMode=False): if errorIndication: print(errorIndication, file=sys.stderr) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'), file=sys.stderr) break else: for varBind in varBinds: res.append(str(varBind)) return res
if __name__ == "__main__":
ptr = NetSNMP("192.168.81.130","public")
ret = ptr.GetNumber("HOST-RESOURCES-MIB","hrMemorySize",0) print("类型: {} --> 返回结果: {} --> 解析: {}".format(type(ret),ret,ret[1]))
ret = ptr.WalkNumber(".1.3.6.1.2.1.2.2.1.6") for each in ret: mac = each.split("=")[1] if len(mac) > 1: print("网卡接口: {}".format(mac))
|