当前位置: 首页>>代码示例>>Python>>正文


Python api.decodeMessageVersion函数代码示例

本文整理汇总了Python中pysnmp.proto.api.decodeMessageVersion函数的典型用法代码示例。如果您正苦于以下问题:Python decodeMessageVersion函数的具体用法?Python decodeMessageVersion怎么用?Python decodeMessageVersion使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了decodeMessageVersion函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: cbFun

def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    while wholeMsg:
        msgVer = int(api.decodeMessageVersion(wholeMsg))
        if api.protoModules.has_key(msgVer):
            pMod = api.protoModules[msgVer]
        else:
            print "Unsupported SNMP version %s" % msgVer
            return
        reqMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())
        print "Notification message from %s:%s: " % (transportDomain, transportAddress)
        reqPDU = pMod.apiMessage.getPDU(reqMsg)
        if reqPDU.isSameTypeWith(pMod.TrapPDU()):
            if msgVer == api.protoVersion1:
                print "Enterprise: %s" % (pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint())
                print "Agent Address: %s" % (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint())
                print "Generic Trap: %s" % (pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint())
                print "Specific Trap: %s" % (pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint())
                print "Uptime: %s" % (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint())
                varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
            else:
                varBinds = pMod.apiPDU.getVarBindList(reqPDU)
            print "Var-binds:"
            for oid, val in varBinds:
                print "%s = %s" % (oid.prettyPrint(), val.prettyPrint())
    return wholeMsg
开发者ID:shimo85,项目名称:pysnmp,代码行数:25,代码来源:ntfrcv.py

示例2: receive_message

    def receive_message(self, host, port, data):
        """ Called when we received a SNMP message on the configured port. """
        snmp_version = int(api.decodeMessageVersion(data))
        if snmp_version in api.protoModules:
            prot_module = api.protoModules[snmp_version]
        elif snmp_version == 3:
            self.parse_snmpv3_trap(data, host)
            return
        else:
            raise UnsupportedSNMPVersion(snmp_version)

        message, temp = decoder.decode(data, asn1Spec=prot_module.Message())
        # print message

        # If configured, check if the community string matches
        recv_community = prot_module.apiMessage.getCommunity(message)
        # print recv_community
        if self.check_community_string and\
            recv_community != self.community_string:
            raise InvalidCommunityString(host, port, recv_community)

        recv_pdu = prot_module.apiMessage.getPDU(message)

        # Only accepting SNMP Trap PDU's
        if not recv_pdu.isSameTypeWith(prot_module.TrapPDU()):
            raise InvalidSNMPType(host, port)

        # Only supporting SNMPv1 and SNMPv2 at the moment
        if snmp_version == api.protoVersion1:
            self.parse_snmpv1_pdu(prot_module, recv_pdu)
        elif snmp_version == api.protoVersion2c:
            self.parse_snmpv2_pdu(prot_module, recv_pdu, host)
        else:
            raise UnsupportedSNMPVersion(snmp_version)
开发者ID:umitproject,项目名称:network-inventory,代码行数:34,代码来源:SNMPListener.py

示例3: cbFun

def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    while wholeMsg:
        msgVer = api.decodeMessageVersion(wholeMsg)
        if msgVer in api.protoModules:
            pMod = api.protoModules[msgVer]
        else:
            print('Unsupported SNMP version %s' % msgVer)
            return
        reqMsg, wholeMsg = decoder.decode(
            wholeMsg, asn1Spec=pMod.Message(),
        )
        rspMsg = pMod.apiMessage.getResponse(reqMsg)
        rspPDU = pMod.apiMessage.getPDU(rspMsg)
        reqPDU = pMod.apiMessage.getPDU(reqMsg)
        varBinds = []
        pendingErrors = []
        errorIndex = 0
        # GETNEXT PDU
        if reqPDU.isSameTypeWith(pMod.GetNextRequestPDU()):
            # Produce response var-binds
            for oid, val in pMod.apiPDU.getVarBinds(reqPDU):
                errorIndex = errorIndex + 1
                # Search next OID to report
                nextIdx = bisect.bisect(mibInstr, oid)
                if nextIdx == len(mibInstr):
                    # Out of MIB
                    varBinds.append((oid, val))
                    pendingErrors.append(
                        (pMod.apiPDU.setEndOfMibError, errorIndex)
                    )
                else:
                    # Report value if OID is found
                    varBinds.append(
                        (mibInstr[nextIdx].name, mibInstr[nextIdx](msgVer))
                    )
        elif reqPDU.isSameTypeWith(pMod.GetRequestPDU()):
            for oid, val in pMod.apiPDU.getVarBinds(reqPDU):
                if oid in mibInstrIdx:
                    varBinds.append((oid, mibInstrIdx[oid](msgVer)))
                else:
                    # No such instance
                    varBinds.append((oid, val))
                    pendingErrors.append(
                        (pMod.apiPDU.setNoSuchInstanceError, errorIndex)
                    )
                    break
        else:
            # Report unsupported request type
            pMod.apiPDU.setErrorStatus(rspPDU, 'genErr')
        pMod.apiPDU.setVarBinds(rspPDU, varBinds)
        # Commit possible error indices to response PDU
        for f, i in pendingErrors:
            f(rspPDU, i)
        transportDispatcher.sendMessage(
            encoder.encode(rspMsg), transportDomain, transportAddress
        )
    return wholeMsg
开发者ID:crazy-canux,项目名称:pysnmp,代码行数:57,代码来源:implementing-scalar-mib-objects.py

示例4: cbFun

    def cbFun(self, transportDispatcher, transportDomain,
            cbCtx, wholeMsg, ):

        print "cbCtx :", cbCtx

        msgVer = int(api.decodeMessageVersion(wholeMsg))
	    #print "Inisde CB FUN..."
           
        
        print 'Inside CB FUN....'

        if msgVer in api.protoModules:
            pMod = api.protoModules[msgVer]
    	else:
            print('Unsupported SNMP version %s' % msgVer)
            #return
    	
        reqMsg, wholeMsg = decoder.decode(
            wholeMsg, asn1Spec=pMod.Message(),
    	)

        self.req = reqMsg

        print 'Type :', type(self.req)

        print 'Inform :', self.inform

        if self.inform:
            print 'Inside Inform IF........'
            if not 'InformRequestPDU()' in str(self.req):
                print 'Inform Message is not sent....failed...'



        print 'reqMsg : %s' % self.req
        #print 'wholeMsg : %s' % wholeMsg

    	#print('Notification message from %s:%s: ' % (
        #    transportDomain, transportAddress
        #    )
    	#)
    	reqPDU = pMod.apiMessage.getPDU(reqMsg)

        print ',,,,reqPDU : %s' % reqPDU
    	varBinds = pMod.apiPDU.getVarBindList(reqPDU)
    	#transportDispatcher.jobFinished(1)
	    
        self.terminationRequestedFlag = True
        if msgVer == api.protoVersion1:
	        self.varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
	        self.specificTrap = pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint()
	        self.version = 1 
	    
        if msgVer == api.protoVersion2c:
	        self.varBinds = pMod.apiPDU.getVarBindList(reqPDU)
	        self.specificTrap = None	
	        self.version = 2
开发者ID:terafastnetworks,项目名称:snmp_trap,代码行数:57,代码来源:trap_receiver.py

示例5: cbFun

    def cbFun(self, transportDispatcher, transportDomain, transportAddress, wholeMsg): #response
        print 'cbFun'
        while wholeMsg:
            msgVer = api.decodeMessageVersion(wholeMsg)
            if msgVer in api.protoModules:
                pMod = api.protoModules[msgVer]
            else:
                print('Unsupported SNMP version %s' % msgVer)
                return
            reqMsg, wholeMsg = decoder.decode(
                wholeMsg, asn1Spec=pMod.Message(),
                )
            rspMsg = pMod.apiMessage.getResponse(reqMsg)
            rspPDU = pMod.apiMessage.getPDU(rspMsg)        
            reqPDU = pMod.apiMessage.getPDU(reqMsg)
            varBinds = []
            pendingErrors = []
            session_data = {}
            errorIndex = 0
            
            # 
            if reqPDU.isSameTypeWith(pMod.SetRequestPDU()):
                #parser
                for oid, val in pMod.apiPDU.getVarBinds(reqPDU):
                    print oid
                    print val
                    if oid in self._mib_instr_idx:
                        session_data[self._mib_instr_idx[oid].title] = str(val)
                        varBinds.append((oid, self._mib_instr_idx[oid](msgVer)))
                    else:
                        # No such instance
                        varBinds.append((oid, val))
                        pendingErrors.append(
                            (pMod.apiPDU.setNoSuchInstanceError, errorIndex)
                            )
                        break
                
            else:
                # Report unsupported request type
                pMod.apiPDU.setErrorStatus(rspPDU, 'genErr')
            
            pMod.apiPDU.setVarBinds(rspPDU, varBinds)
            
            try:
                self._fakebras.stop_session(session_data, True)
            except Exception as error:
                raise

            # Commit possible error indices to response PDU
            for f, i in pendingErrors:
                f(rspPDU, i)
            
            transportDispatcher.sendMessage(
                encoder.encode(rspMsg), transportDomain, transportAddress
                )
        return wholeMsg
开发者ID:EMamoshin,项目名称:fakebras,代码行数:56,代码来源:snmp_agent.py

示例6: cbFun

def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    global count_i
    while wholeMsg:
        msgVer = int(api.decodeMessageVersion(wholeMsg))
        if msgVer in api.protoModules:
            pMod = api.protoModules[msgVer]
        else:
            print('Unsupported SNMP version %s' % msgVer)
            return
        reqMsg, wholeMsg = decoder.decode(
            wholeMsg, asn1Spec=pMod.Message(),
            )
        print '\nIndex: %d********************************************************************************' % count_i
        print('Notification message from %s:%s: ' % (
            transportDomain, transportAddress
            )
        )
        reqPDU = pMod.apiMessage.getPDU(reqMsg)
        if reqPDU.isSameTypeWith(pMod.TrapPDU()):
            if msgVer == api.protoVersion1:
                print('Enterprise: %s' % (
                    pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint()
                    )
                )
                print('Agent Address: %s' % (
                    pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()
                    )
                )
                print('Generic Trap: %s' % (
                    pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()
                    )
                )
                print('Specific Trap: %s' % (
                    pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint()
                    )
                )
                print('Uptime: %s' % (
                    pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint()
                    )
                )
                varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
            else:
                varBinds = pMod.apiPDU.getVarBindList(reqPDU)
            # print('Var-binds:')
            # print 'oid\t\t\ttype\t\t\tvalue'
            print 'OID' + ' ' * 32 + 'VALUE'
            for oid, val in varBinds:
                # print('%s = %s' % (oid.prettyPrint(), val.prettyPrint().encode('utf-8')))
                oid = oid.prettyPrint()
                sva = val.prettyPrint().encode('utf-8')
                spr = sva[sva.rfind('value=') + 6:].strip()
                print oid + ' ' * (35 - len(oid)) + spr
                # prt = spr.split('=')
                # print '%s\t\t\t%s\t\t\t%s' % (oid, prt[0], prt[1])
    return wholeMsg
开发者ID:lowitty,项目名称:zacademy,代码行数:55,代码来源:trapreciever_v1v2.py

示例7: onSnmpMessage

	def onSnmpMessage(self, transportDispatcher, transportDomain, transportAddress, wholeMsg):
		while wholeMsg:
			msgVer = api.decodeMessageVersion(wholeMsg)
			if api.protoModules.has_key(msgVer):
				pMod = api.protoModules[msgVer]
			else:
				getLogger().error('Unsupported SNMP version %s' % msgVer)
				return
			reqMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message(), )
			rspMsg = pMod.apiMessage.getResponse(reqMsg)
			rspPDU = pMod.apiMessage.getPDU(rspMsg)		
			reqPDU = pMod.apiMessage.getPDU(reqMsg)
			varBinds = []
			errorIndex = -1

			# GET request
			if reqPDU.isSameTypeWith(pMod.GetRequestPDU()):
				getLogger().info("SNMP GET received...")
				for oid, val in pMod.apiPDU.getVarBinds(reqPDU):
					getLogger().debug("Trying to GET %s... " % oidToString(oid))
					if mibVariablesByOid.has_key(oid):
						varBinds.append((oid, mibVariablesByOid[oid](msgVer)))
					else:
						# No such instance
						pMod.apiPDU.setNoSuchInstanceError(rspPDU, errorIndex)
						varBinds = pMod.apiPDU.getVarBinds(reqPDU)
						break

			# GET-NEXT request
			elif reqPDU.isSameTypeWith(pMod.GetNextRequestPDU()):
				getLogger().info("SNMP GET-NEXT received...")
				# Produce response var-binds
				errorIndex = -1
				for oid, val in pMod.apiPDU.getVarBinds(reqPDU):
					getLogger().debug("Trying to GET-NEXT %s... " % oidToString(oid))
					errorIndex = errorIndex + 1
					# Search next OID to report
					nextIdx = bisect.bisect(mibVariables, oid)
					if nextIdx == len(mibVariables):
						# Out of MIB
						pMod.apiPDU.setEndOfMibError(rspPDU, errorIndex)
					else:
						# Report value if OID is found
						varBinds.append((mibVariables[nextIdx].oid, mibVariables[nextIdx](msgVer)))

			else:
				getLogger().error("Unsupported SNMP request received...")
				# Report unsupported request type
				pMod.apiPDU.setErrorStatus(rspPDU, -1) # we should use something different from -1

			pMod.apiPDU.setVarBinds(rspPDU, varBinds)
			transportDispatcher.sendMessage(encoder.encode(rspMsg), transportDomain, transportAddress)
		return wholeMsg
开发者ID:rolfschr,项目名称:testerman,代码行数:53,代码来源:Snmp.py

示例8: newFn

def newFn(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    print "Lights status:"
    print lights[0]
    while wholeMsg:
        msgVer = int(api.decodeMessageVersion(wholeMsg))
        if msgVer in api.protoModules:
            pMod = api.protoModules[msgVer]
        else:
            print('Unsupported SNMP version %s' % msgVer)
            return
        reqMsg, wholeMsg = decoder.decode(
            wholeMsg, asn1Spec=pMod.Message(),
            )
        """
        print('Notification message from %s:%s: %s ' % (
            transportDomain, transportAddress, wholeMsg
            )
        )
        """
        reqPDU = pMod.apiMessage.getPDU(reqMsg)
        if reqPDU.isSameTypeWith(pMod.TrapPDU()):
            if msgVer == api.protoVersion1:
                """
                print('Enterprise: %s' % (
                    pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint()
                    )
                )
                print('Agent Address: %s' % (
                    pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()
                    )
                )
                print('Generic Trap: %s' % (
                    pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()
                    )
                )
                print('Specific Trap: %s' % (
                    pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint()
                    )
                )
                print('Uptime: %s' % (
                    pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint()
                    )
                )
                """
                varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
            else:
                varBinds = pMod.apiPDU.getVarBindList(reqPDU)
            for oid, val in varBinds:
                #print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
                print "RECEIVED a TRAP Message from Light Agent :"
                lights[0] = (((str(val).split("OctetString('"))[1]).split("')))"))[0]
                print (((str(val).split("OctetString('"))[1]).split("')))"))[0]
    return wholeMsg
开发者ID:stephenoken,项目名称:-SNMP-Management-Station-for-Wireless-Indoor-Network,代码行数:53,代码来源:manager.py

示例9: _trap_receiver_cb

    def _trap_receiver_cb(transport, domain, sock, msg):
        if decodeMessageVersion(msg) != protoVersion2c:
            raise RuntimeError('Only SNMP v2c traps are supported.')

        req, msg = decoder.decode(msg, asn1Spec=v2c.Message())
        pdu = v2c.apiMessage.getPDU(req)

        # ignore any non trap PDUs
        if not pdu.isSameTypeWith(v2c.TrapPDU()):
            return

        if trap_filter(domain, sock, pdu):
            transport.jobFinished(1)
开发者ID:urtow,项目名称:robotframework-snmplibrary,代码行数:13,代码来源:traps.py

示例10: trapCallback

def trapCallback(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    
    try:
        if not wholeMsg:
            logging.error('Receiving trap , error processing the inital message in the trapCallback handler')
            
        while wholeMsg:
            msgVer = int(api.decodeMessageVersion(wholeMsg))
            if msgVer in api.protoModules:
                pMod = api.protoModules[msgVer]
            else:
                logging.error('Receiving trap , unsupported SNMP version %s' % msgVer)
                return
            reqMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message(),)
            
            reqPDU = pMod.apiMessage.getPDU(reqMsg)
            
            trap_metadata =""
            server = ""
            try:
                server = "%s" % transportAddress[0]
                trap_metadata += 'notification_from_address = "%s" ' % (transportAddress[0])
                trap_metadata += 'notification_from_port = "%s" ' % (transportAddress[1])
            except: # catch *all* exceptions
                e = sys.exc_info()[1]
                logging.error("Exception resolving source address/domain of the trap: %s" % str(e))
            
            if reqPDU.isSameTypeWith(pMod.TrapPDU()):
                if msgVer == api.protoVersion1:
                    if server == "":
                        server = pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()

                    trap_metadata += 'notification_enterprise = "%s" ' % (pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint())
                    trap_metadata += 'notification_agent_address = "%s" ' % (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint())
                    trap_metadata += 'notification_generic_trap = "%s" ' % (pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint())
                    trap_metadata += 'notification_specific_trap = "%s" ' % (pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint())
                    trap_metadata += 'notification_uptime = "%s" ' % (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint())
                    
                    varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
                else:
                    varBinds = pMod.apiPDU.getVarBindList(reqPDU)
                    
                      
                
            handle_output(varBinds,server,from_trap=True,trap_metadata=trap_metadata) 
            
    except: # catch *all* exceptions
        e = sys.exc_info()[1]
        logging.error("Exception receiving trap %s" % str(e))
                  
    return wholeMsg        
开发者ID:cjthuys,项目名称:SplunkModularInputsPythonFramework,代码行数:51,代码来源:snmp.py

示例11: cbFun

 def cbFun(self,transportDispatcher, transportDomain, transportAddress, wholeMsg):  
     record = '' 
     record = record + '<snmpTrapPdu xmlns="http://huawei.com/common/trap">\n' 
     while wholeMsg:
         msgVer = int(api.decodeMessageVersion(wholeMsg))
         if msgVer in api.protoModules:
             pMod = api.protoModules[msgVer]
         else:
             logger.warning('Unsupported SNMP version %s' % msgVer)
             return
         reqMsg, wholeMsg = decoder.decode(
             wholeMsg, asn1Spec=pMod.Message(),
             )                             
         #logger.warning('Notification message from %s:%s: ' % (transportDomain, transportAddress))
         reqPDU = pMod.apiMessage.getPDU(reqMsg)
         community = pMod.apiMessage.getCommunity(reqMsg)
         timestamp = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
         
         if reqPDU.isSameTypeWith(pMod.TrapPDU()):
             if msgVer == api.protoVersion1:                    
                 Enterprise = (str)(pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint()) 
                 agentaddr = pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()
                 GenericTrapid = pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()
                 SpecificTrapid = pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint()
                 varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
             else:                     
                 varBinds = pMod.apiPDU.getVarBindList(reqPDU) 
                 trapoid =  (str)(varBinds[1][1][0][0][2])
            
             ReceivedTrap = SnmpTrap(msgVer,transportDomain,transportAddress,varBinds)  
             
             trapvbs = ''
             for oid, val in varBinds:
                 #logger.warning ('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) 
                 trapvbs = trapvbs + '<vb>'  
                 trapvbs = trapvbs + '\n        <oid>' + oid.prettyPrint() + '</oid>' 
                 #print (val.getComponent(1)).prettyPrint()
                 value = (val.getComponent(1)).prettyPrint()
                 trapvbs = trapvbs + '\n        <value>' + value + '</value>\n'  
                 trapvbs = trapvbs + '        </vb>\n'  
                        
             #no print community message
             if msgVer == api.protoVersion1:
                 traprecord = v1trapformat%(timestamp,agentaddr,Enterprise,GenericTrapid,SpecificTrapid,trapvbs)
             else:
                 traprecord = v2trapformat%(timestamp,transportAddress[0],trapoid,trapvbs)
             #print traprecord     
             logger.warning(traprecord)                          
             for i in self._dispatchers:                    
                 i.dispatch(ReceivedTrap, traprecord)
开发者ID:my76128,项目名称:OPS2,代码行数:50,代码来源:snmp_traprcv.py

示例12: _on_trap

    def _on_trap(self, transport_dispatcher, transport_domain,
                 transport_address, whole_msg):
        """ This method is called from pysnmp whenever a trap is received
        """
        self.logger.debug('Trap received')
        signals = []
        while whole_msg:
            signal_data = {}
            msg_ver = int(api.decodeMessageVersion(whole_msg))
            if msg_ver in api.protoModules:
                p_mod = api.protoModules[msg_ver]
            else:
                self.logger.warning('Unsupported SNMP version %s' % msg_ver)
                return
            req_msg, whole_msg = decoder.decode(
                whole_msg, asn1Spec=p_mod.Message(),)

            self.logger.info('Notification message from %s:%s: ' % (
                transport_domain, transport_address))
            signal_data["transport_domain"] = \
                str(oid_parser(transport_domain))
            signal_data["transport_address"] = \
                str(oid_parser(transport_address))

            req_pdu = p_mod.apiMessage.getPDU(req_msg)
            if req_pdu.isSameTypeWith(p_mod.TrapPDU()):
                if msg_ver == api.protoVersion1:
                    signal_data["enterprise"] = \
                        p_mod.apiTrapPDU.getEnterprise(req_pdu).prettyPrint()
                    signal_data["agent address"] = \
                        p_mod.apiTrapPDU.getAgentAddr(req_pdu).prettyPrint()
                    signal_data["generic trap"] = \
                        p_mod.apiTrapPDU.getGenericTrap(req_pdu).prettyPrint()
                    signal_data["specific trap"] = \
                        p_mod.apiTrapPDU.getSpecificTrap(req_pdu).prettyPrint()
                    signal_data["uptime"] = \
                        p_mod.apiTrapPDU.getTimeStamp(req_pdu).prettyPrint()
                    var_binds = p_mod.apiTrapPDU.getVarBindList(req_pdu)
                else:
                    var_binds = p_mod.apiPDU.getVarBindList(req_pdu)
                signal_data["var-binds"] = {}
                for item in var_binds:
                    oid = item[0]
                    val = item[1]
                    signal_data["var-binds"][str(oid_parser(oid._value))] = \
                        self._get_var_bind_data(val)
            signals.append(Signal(signal_data))
        if len(signals):
            self.notify_signals(signals, "trap")
开发者ID:nio-blocks,项目名称:snmp,代码行数:49,代码来源:snmp_trap_block.py

示例13: unpack_msg

    def unpack_msg(self, msg):
        """Unpack a SNMP message
        """
        self.version = api.decodeMessageVersion(msg)
        pMod = api.protoModules[int(self.version)]

        snmp_msg, m = decoder.decode(msg,
                                     asn1Spec=pMod.Message())
        snmp_pdu = pMod.apiMessage.getPDU(snmp_msg)
        snmp_error = pMod.apiPDU.getErrorStatus(snmp_pdu)

        self.community = pMod.apiMessage.getCommunity(snmp_msg)
        self.isTrap = snmp_pdu.isSameTypeWith(pMod.TrapPDU())

        return (snmp_msg, snmp_pdu, snmp_error)
开发者ID:sharifelshenawy,项目名称:yapc,代码行数:15,代码来源:snmp.py

示例14: handleSnmpMessage

def handleSnmpMessage(d, t, private={}):
    msgVer = api.decodeMessageVersion(d['data'])
    if msgVer in api.protoModules:
        pMod = api.protoModules[msgVer]
    else:
        stats['bad packets'] +=1
        return
    try:
        rspMsg, wholeMsg = decoder.decode(
            d['data'], asn1Spec=pMod.Message(),
        )
    except PyAsn1Error:
        stats['bad packets'] +=1
        return
    if rspMsg['data'].getName() == 'response':
        rspPDU = pMod.apiMessage.getPDU(rspMsg)
        errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)
        if errorStatus:
            stats['SNMP errors'] +=1
        else:
            endpoint = d['source_address'], d['source_port']
            if endpoint not in endpoints:
                endpoints[endpoint] = udp.domainName + (transportIdOffset + len(endpoints),)
                stats['agents seen'] +=1
            context = '%s/%s' % (pMod.ObjectIdentifier(endpoints[endpoint]), pMod.apiMessage.getCommunity(rspMsg))
            if context not in contexts:
                contexts[context] = {}
                stats['contexts seen'] +=1
            context = '%s/%s' % (pMod.ObjectIdentifier(endpoints[endpoint]), pMod.apiMessage.getCommunity(rspMsg))

            stats['Response PDUs seen'] += 1

            if 'basetime' not in private:
                private['basetime'] = t

            for oid, value in pMod.apiPDU.getVarBinds(rspPDU):
                if oid < startOID:
                    continue
                if stopOID and oid >= stopOID:
                    continue
                if oid in contexts[context]:
                    if value != contexts[context][oid]:
                        stats['snapshots taken'] +=1
                else:
                    contexts[context][oid] = [], []
                contexts[context][oid][0].append(t - private['basetime'])
                contexts[context][oid][1].append(value)
                stats['OIDs seen'] += 1
开发者ID:woodyle,项目名称:snmpsim,代码行数:48,代码来源:pcap2dev.py

示例15: cbFun

def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
	while wholeMsg:
		msgVer = int(api.decodeMessageVersion(wholeMsg))
		if api.protoModules.has_key(msgVer):
			pMod = api.protoModules[msgVer]
		else:
			print 'Unsupported SNMP version %s' % msgVer
			return

		reqMsg, wholeMsg = decoder.decode( wholeMsg, asn1Spec=pMod.Message())

		#print 'Trap from %s[%s]:' % transportAddress

		reqPDU = pMod.apiMessage.getPDU(reqMsg)
		if reqPDU.isSameTypeWith(pMod.TrapPDU()):
			if msgVer == api.protoVersion1:
				agent		= pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()
				enterprise	= str(pMod.apiTrapPDU.getEnterprise(reqPDU))
				gtrap		= str(pMod.apiTrapPDU.getGenericTrap(reqPDU))
				strap		= str(pMod.apiTrapPDU.getSpecificTrap(reqPDU))
				varBinds 	= pMod.apiTrapPDU.getVarBindList(reqPDU)
				timestamp 	= pMod.apiTrapPDU.getTimeStamp(reqPDU)

				trap_oid = enterprise + '.0.' + strap

				if enterprise in snmp2amqp_conf.blacklist_enterprise:
					logger.debug("Blacklist enterprise: '%s'." % enterprise)
					return wholeMsg

				if trap_oid in snmp2amqp_conf.blacklist_trap_oid:
					logger.debug("Blacklist trap: '%s'." % trap_oid)
					return wholeMsg

				mib = None
				try:
					mib = mibs[enterprise]
				except:	
					logger.warning("Unknown trap from '%s': %s" % (agent, trap_oid))
					logger.warning(" + Unknown enterprise '%s'" % enterprise)
					#if varBinds:
					#	for oid, components in varBinds:
					#		print "  + ", oid

				if mib:
					try:
						parse_trap(mib, trap_oid, agent, varBinds)
					except Exception, err:
						logger.error("Impossible to parse trap: %s" % err)
开发者ID:EzanLTD,项目名称:canopsis,代码行数:48,代码来源:snmp2amqp.py


注:本文中的pysnmp.proto.api.decodeMessageVersion函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。