def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform SNMP GET query. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP GET request is send (:RFC:`1905#section-4.2.1`). The iterator yields :py:class:`asyncio.Future` which gets done whenever response arrives or error occurs. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncio.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncio.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to `varBinds[errorIndex-1]` varBinds : tuple A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> import asyncio >>> from pysnmp.hlapi.asyncio import * >>> >>> @asyncio.coroutine ... def run(): ... errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( ... SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) ... ) ... print(errorIndication, errorStatus, errorIndex, varBinds) >>> >>> asyncio.get_event_loop().run_until_complete(run()) (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, future = cbCtx if future.cancelled(): return try: varBindsUnmade = vbProcessor.unmakeVarBinds( snmpEngine, varBinds, lookupMib) except Exception as e: future.set_exception(e) else: future.set_result( (errorIndication, errorStatus, errorIndex, varBindsUnmade)) addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget) future = asyncio.Future() cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), future)) return future
def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP GET query. Based on passed parameters, prepares SNMP GET packet (:RFC:`1905#section-4.2.1`) and schedules its transmission by I/O framework at a later point of time. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. * `cbFun` (callable) - user-supplied callable that is invoked to pass SNMP response data or error to user at a later point of time. Default is `None`. * `cbCtx` (object) - user-supplied object passing additional parameters to/from `cbFun`. Default is `None`. Notes ----- User-supplied `cbFun` callable must have the following call signature: * snmpEngine (:py:class:`~pysnmp.hlapi.SnmpEngine`): Class instance representing SNMP engine. * sendRequestHandle (int): Unique request identifier. Can be used for matching multiple ongoing requests with received responses. * errorIndication (str): True value indicates SNMP engine error. * errorStatus (str): True value indicates SNMP PDU error. * errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]` * varBinds (tuple): A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response in exactly the same order as `varBinds` in request. * `cbCtx` : Original user-supplied object. Returns ------- sendRequestHandle : int Unique request identifier. Can be used for matching received responses with ongoing requests. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> from pysnmp.hlapi.asyncore import * >>> def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): ... print(errorIndication, errorStatus, errorIndex, varBinds) >>> >>> snmpEngine = SnmpEngine() >>> getCmd(snmpEngine, ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ... cbFun=cbFun) >>> snmpEngine.transportDispatcher.runDispatcher() (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, cbFun, cbCtx = cbCtx if cbFun: return cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, vbProcessor.unmakeVarBinds( snmpEngine, varBinds, lookupMib ), cbCtx) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) return cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), options.get('cbFun'), options.get('cbCtx')) )
# Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message, pass custom ContextEngineId & ContextName cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', # contextEngineId rfc1902.OctetString(hexValue='80004fb805636c6f75644dab22cc'), # contextName rfc1902.OctetString('da761cfc8c94d3aceef4f60f049105ba'), [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher()
try: # Parse c/l into AST ast = Parser().parse(Scanner().tokenize(' '.join(sys.argv[1:]))) ctx = {} # Apply configuration to SNMP entity main.generator((snmpEngine, ctx), ast) msgmod.generator((snmpEngine, ctx), ast) secmod.generator((snmpEngine, ctx), ast) mibview.generator((snmpEngine, ctx), ast) target.generator((snmpEngine, ctx), ast) pdu.readPduGenerator((snmpEngine, ctx), ast) cmdgen.GetCommandGenerator().sendVarBinds(snmpEngine, ctx['addrName'], ctx.get('contextEngineId'), ctx.get('contextName', ''), ctx['varBinds'], cbFun, ctx) snmpEngine.transportDispatcher.runDispatcher() except KeyboardInterrupt: sys.stderr.write('Shutting down...\n') except error.PySnmpError: sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage())) sys.exit(-1) except Exception: sys.stderr.write('Process terminated\n') for line in traceback.format_exception(*sys.exc_info()): sys.stderr.write(line.replace('\n', ';'))
# Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() config.delTransport(snmpEngine, udp.domainName).closeTransport()
def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP GET query. Based on passed parameters, prepares SNMP GET packet (:RFC:`1905#section-4.2.1`) and schedules its transmission by :mod:`twisted` I/O framework at a later point of time. Parameters ---------- snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Returns ------- deferred : :class:`~twisted.internet.defer.Deferred` Twisted Deferred object representing work-in-progress. User is expected to attach his own `success` and `error` callback functions to the Deferred object though :meth:`~twisted.internet.defer.Deferred.addCallbacks` method. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- User `success` callback is called with the following tuple as its first argument: * errorStatus (str) : True value indicates SNMP PDU error. * errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]` * varBinds (tuple) : A sequence of :class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. User `error` callback is called with `errorIndication` object wrapped in :class:`~twisted.python.failure.Failure` object. Examples -------- >>> from twisted.internet.task import react >>> from pysnmp.hlapi.twisted import * >>> >>> def success((errorStatus, errorIndex, varBinds)): ... print(errorStatus, errorIndex, varBind) ... >>> def failure(errorIndication): ... print(errorIndication) ... >>> def run(reactor): ... d = getCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) ... d.addCallback(success).addErrback(failure) ... return d ... >>> react(run) (0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, deferred = cbCtx if errorIndication: deferred.errback(Failure(errorIndication)) else: deferred.callback( (errorStatus, errorIndex, vbProcessor.unmakeVarBinds(snmpEngine, varBinds, lookupMib))) addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget) deferred = Deferred() cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), deferred)) return deferred
def snmpv3_get(ip='', user='', hash_meth=None, hash_key=None, cry_meth=None, cry_key=None, oid=''): #usmHMACMD5AuthProtocol - MD5 hashing #usmHMACSHAAuthProtocol - SHA hashing #usmNoAuthProtocol - no authentication #usmDESPrivProtocol - DES encryption #usm3DESEDEPrivProtocol - triple-DES encryption #usmAesCfb128Protocol - AES encryption, 128-bit #usmAesCfb192Protocol - AES encryption, 192-bit #usmAesCfb256Protocol - AES encryption, 256-bit #usmNoPrivProtocol - no encryption hashval = None cryval = None model = None config.addTargetAddr( #添加目标,'yourDevice'(OID与处理方法),'my-creds'(用户,密码,安全模型),目的IP与端口号 snmpEngine, 'yourDevice', udp.domainName, (ip, 161), 'my-creds') #========================下面的操作在判断安全模型========================== #NoAuthNoPriv if hash_meth == None and cry_meth == None: hashval = config.usmNoAuthProtocol cryval = config.usmNoPrivProtocol model = 'noAuthNoPriv' #AuthNoPriv elif hash_meth != None and cry_meth == None: if hash_meth == 'md5': hashval = config.usmHMACMD5AuthProtocol elif hash_meth == 'sha': hashval = config.usmHMACSHAAuthProtocol else: print('哈希算法必须是md5 or sha!') return cryval = config.usmNoPrivProtocol model = 'authNoPriv' #AuthPriv elif hash_meth != None and cry_meth != None: if hash_meth == 'md5': hashval = config.usmHMACMD5AuthProtocol elif hash_meth == 'sha': hashval = config.usmHMACSHAAuthProtocol else: print('哈希算法必须是md5 or sha!') return if cry_meth == '3des': cryval = config.usm3DESEDEPrivProtocol elif cry_meth == 'des': cryval = config.usmDESPrivProtocol elif cry_meth == 'aes128': cryval = config.usmAesCfb128Protocol elif cry_meth == 'aes192': cryval = config.usmAesCfb192Protocol elif cry_meth == 'aes256': cryval = config.usmAesCfb256Protocol else: print('加密算法必须是3des, des, aes128, aes192 or aes256 !') return model = 'authPriv' #提供的参数不符合标准时给出提示 else: print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。') return #========================判断安全模型结束========================== config.addV3User( #添加用户与他的密钥 snmpEngine, user, hashval, hash_key, cryval, cry_key) config.addTargetParams(snmpEngine, 'my-creds', user, model) #创建'my-creds',里边有用户和安全模型 # Prepare and send a request message cmdgen.GetCommandGenerator().sendReq( snmpEngine, 'yourDevice', #创建'yourDevice',有OID和处理方法cbFun ((oid, None), ), cbFun) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() #运行实例 return oid_list #返回oid_list
'myParams') config.addSocketTransport(snmp_engine, udp.domainName, udp.UdpSocketTransport().openClientMode()) cb = {} def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBinds'] = varBinds cmdgen.GetCommandGenerator().sendReq(snmp_engine, 'myRouter', ((sysName, None), ), cbFun, cb) lastmemusage = 0 lastrefs = None errors = 0 while (errors < 2): snmp_engine.transportDispatcher.runDispatcher() print cb['varBinds'][0][1] newmemusage = resource.getrusage(resource.RUSAGE_SELF)[2] memdiff = (newmemusage - lastmemusage) newrefs = get_refcounts() if memdiff > 0: print "Leaked %d Kb... printing refcount diff" % memdiff if lastrefs == None: print "No previous refcount, skipping" else:
('127.0.0.1', 161), 'myParams') # Setup transport endpoint config.addSocketTransport(snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()) def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBinds'] = varBinds # Used to pass data from callback function cbCtx = {} cmdgen.GetCommandGenerator().sendReq(snmpEngine, 'myRouter', (((1, 3, 6, 1, 2, 1, 1, 1, 0), None), ), cbFun, cbCtx) snmpEngine.transportDispatcher.runDispatcher() if cbCtx['errorIndication']: print cbCtx['errorIndication'] elif cbCtx['errorStatus']: print cbCtx['errorStatus'].prettyPrint() else: for oid, val in cbCtx['varBinds']: print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
context_data = ContextData() snmpEngine = engine.SnmpEngine() target = register_device_target( host, port, timeout=3, retries=3, engine=snmpEngine, auth_data=auth_data, context_data=context_data, ) sessions.append((snmpEngine, target)) start = time.time() for snmpEngine, target in sessions: for _ in range(rounds): cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, target, None, context_name, # contextEngineId, contextName oids, callback_fn ) snmpEngine.transportDispatcher.runDispatcher() end = time.time() print("pysnmp duration: {:.2f} ms".format((end - start) * 1000))
class CommandResponder(cmdrsp.CommandResponderBase): cmdGenMap = { v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun() } pduTypes = cmdGenMap.keys() # This app will handle these PDUs # SNMP request relay def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): cbCtx = snmpEngine, stateReference varBinds = v2c.apiPDU.getVarBinds(PDU) print "Begin of handleMgmtOperation" try: if contextName not in agentMap: raise PySnmpError('Unknown context name %s' % contextName) # Select backend Agent ID by contextName arrived with request targetName, targetAddress = agentMap[contextName] isCached = 1 indice = 0 print "Beginning to check all of cache" for oid in varBinds: k, v = oid key = targetAddress + "-" + str(oid[0]) print "Checking cache for oid: " + str(oid[0]) if r.exists(key) == True: v = r.get(key) varBinds[indice] = (k, v) indice = indice + 1 print "Key Cached: " + str(k) #self.sendRsp(snmpEngine, stateReference, 0, 0, varBinds) else: isCached = 0 print "Not all entries cached: " + str(k) #break if isCached == 1: print "All cached - sending cached response" self.sendRsp(snmpEngine, stateReference, 0, 0, varBinds) elif isCached == 0: print "Not all cached - sending request" if PDU.tagSet == v2c.GetBulkRequestPDU.tagSet: self.cmdGenMap[PDU.tagSet].sendReq( snmpEngine, targetName, v2c.apiBulkPDU.getNonRepeaters(PDU), v2c.apiBulkPDU.getMaxRepetitions(PDU), varBinds, self.handleResponse, cbCtx) elif PDU.tagSet in self.cmdGenMap: self.cmdGenMap[PDU.tagSet].sendReq(snmpEngine, targetName, varBinds, self.handleResponse, cbCtx) except error.PySnmpError: print sys.exc_info()[1] self.handleResponse(stateReference, 'error', 0, 0, varBinds, cbCtx) # SNMP response relay def handleResponse(self, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: errorStatus = 5 errorIndex = 0 varBinds = () snmpEngine, stateReference = cbCtx hosts = snmpEngine.cache['getTargetAddr']['nameToTargetMap'] host = "" for key in hosts.items(): k, v = key host = v[1][0] for a in varBinds: key = str(host) + "-" + str(a[0]) print "Caching Key: " + key r.setex(key, 120, a[1]) print "Sending uncached response to client" self.sendRsp(snmpEngine, stateReference, errorStatus, errorIndex, varBinds)