def message_received(self, transport_dispatcher, transport_domain,
                         transport_address, whole_message):
        while whole_message:
            message_version = api.decodeMessageVersion(whole_message)
            protocol = api.protoModules[message_version]

            request_message, whole_message = decoder.decode(
                whole_message, asn1Spec=protocol.Message())
            request_pdu = protocol.apiMessage.getPDU(request_message)
            response_msg = protocol.apiMessage.getResponse(request_message)
            response_pdu = protocol.apiMessage.getPDU(response_msg)
            community = protocol.apiMessage.getCommunity(request_message)

            if not self._is_valid_community(community):
                break

            if request_pdu.isSameTypeWith(protocol.GetRequestPDU()):
                self._get_request(protocol, request_pdu, response_pdu)
            elif request_pdu.isSameTypeWith(protocol.GetNextRequestPDU()):
                self._get_next_request(protocol, request_pdu, response_pdu)
            elif request_pdu.isSameTypeWith(protocol.SetRequestPDU()):
                self._set_request(protocol, request_pdu, response_pdu)
            else:
                self._error(protocol, response_pdu)

            transport_dispatcher.sendMessage(encoder.encode(response_msg),
                                             transport_domain,
                                             transport_address)
        return whole_message
Пример #2
0
    def _callback(self, transport_dispatcher, transport_domain,
                  transport_address, whole_msg):
        try:
            while whole_msg:
                msg_version = int(api.decodeMessageVersion(whole_msg))
                if msg_version not in api.protoModules:
                    logger.error('Unsupported SNMP version {} {}'.format(
                        msg_version, transport_address[0]))
                    return

                proto_module = api.protoModules[msg_version]

                request_msg, whole_msg = decoder.decode(
                    whole_msg,
                    asn1Spec=proto_module.Message(),
                )
                request_pdu = proto_module.apiMessage.getPDU(request_msg)
                if transport_address[0] == '0.0.0.0':
                    logger.info('Broadcast snmptrap ignored')
                    return
                if request_pdu.isSameTypeWith(proto_module.TrapPDU()):
                    self._extract_and_process_trap(proto_module, request_pdu,
                                                   transport_address)
        except Exception as exc:
            logger.critical('Error snmptrap: {}  {}'.format(
                exc, exc.__class__.__name__))
Пример #3
0
 def cbFun(self, transportDispatcher, transportDomain, transportAddress, wholeMsg):
     """ this callback function which will handle the snmptrap message from pysnmp stack """
     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 SnmpdThread.database:
                 conn = SnmpdThread.database.open()
                 root = conn.root()
                 root_folder = root['Application']
                 old_site = getSite()
                 setSite(root_folder)
                 my_catalog = zapi.getUtility(ICatalog)
                 search_ip = pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()
                 search_ip_conv = convertIpV4(search_ip)
                 for result in my_catalog.searchResults(\
                     interface_ip_index=search_ip_conv):
                     parentObj = result.__parent__
                     snmpAdapter = ISnmptrapd(parentObj)
                     snmpAdapter.triggered(reqPDU, msgVer, pMod)
                 setSite(old_site)
                 transaction.commit()
                 conn.close()
     return wholeMsg
Пример #4
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    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: ' % (
            transportDomain, transportAddress
        )
              )
        reqPDU = pMod.apiMessage.getPDU(reqMsg)
        text = ''
        if reqPDU.isSameTypeWith(pMod.TrapPDU()):
            if msgVer == api.protoVersion1:
                text = text + 'Enterprise: ' + pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint() + '\n'
                # Incluir el resto de campos del trap que se consideren oportunos

                varBinds = pMod.apiTrapPDU.getVarBinds(reqPDU)
            else:
                varBinds = pMod.apiPDU.getVarBinds(reqPDU)

            # Incluir el contenido de las varBinds en el correo electronico





    return wholeMsg
Пример #5
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    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: ' %
              (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
Пример #6
0
    def recv_trap(self, recv_addr, recv_msg):
        # Fix the IPv4 mapped addresses
        if recv_addr[0][:7] == '::ffff:':
            host_ip = recv_addr[0][7:]
        else:
            host_ip = recv_addr[0]
        host_id = self._get_host_id(host_ip)
        if host_id is None:
            self.logger.debug('Notification message from unknown host %s',
                              host_ip)
            return
        while recv_msg:
            msg_ver = int(api.decodeMessageVersion(recv_msg))
            if msg_ver in api.protoModules:
                pmod = api.protoModules[msg_ver]
            else:
                self.logger.info('H:%d - Unsupported SNMP version %s from %s',
                                 host_id, msg_ver, host_ip)
                return

            req_msg, recv_msg = decoder.decode(
                recv_msg,
                asn1Spec=pmod.Message(),
            )

            req_pdu = pmod.apiMessage.getPDU(req_msg)
            if req_pdu.isSameTypeWith(pmod.TrapPDU()):
                trap_oid = None

                if msg_ver == api.protoVersion1:
                    trap_oid = self._get_trapv1_oid(pmod, req_pdu)
                    if trap_oid is None:
                        return
                    new_trap = SnmpTrap(host_id, trap_oid)
                    new_trap.set_uptime(
                        pmod.apiTrapPDU.getTimeStamp(req_pdu).prettyPrint())
                    var_binds = pmod.apiTrapPDU.getVarBindList(req_pdu)
                else:
                    new_trap = SnmpTrap(host_id, None)
                    var_binds = pmod.apiPDU.getVarBindList(req_pdu)

                for var_bind in var_binds:
                    oid, val = pmod.apiVarBind.getOIDVal(var_bind)
                    if oid == SNMP_TRAP_OID:
                        new_trap.trap_oid = val.prettyPrint()
                    else:
                        new_trap.set_varbind(oid.prettyPrint(),
                                             val.prettyPrint())
                if new_trap.trap_oid is None:
                    self.logger.info('H:%d Trap with no trap_oid?')
                else:
                    if self._duplicate_trap(host_id, new_trap.trap_oid):
                        self.logger.debug(
                            'H:%d Duplicate Trap,not added OID:%s', host_id,
                            new_trap.trap_oid)
                    else:
                        self.logger.debug('H:%d New Trap v%s OID:%s', host_id,
                                          msg_ver, new_trap.trap_oid)
                        DBSession.add(new_trap)
                        transaction.commit()
Пример #7
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    try:
        #Enables pysmi debugging
        #debug.setLogger(debug.Debug('reader'))

        # Assemble MIB viewer
        mibBuilder = builder.MibBuilder()
        mibViewController = view.MibViewController(mibBuilder)

        # Pre-load MIB modules we expect to work with
        try:
            mibBuilder.loadModules('SNMPv2-MIB')
        except:
            logging.error("Fail loading mibs")

        # vars to store, match here the MIB field you need to save
        # cLApName = '1.3.6.1.4.1.9.9.513.1.1.1.1.5.0'
        # cLApRogueApMacAddress = '1.3.6.1.4.1.9.9.513.3.2.0'
        # cLApDot11IfType = '1.3.6.1.4.1.9.9.513.1.2.1.1.2.0'

        while wholeMsg:
            msgVer = int(api.decodeMessageVersion(wholeMsg))
            if msgVer in api.protoModules:
                pMod = api.protoModules[msgVer]
            else:
                print('Unsupported SNMP version %s' % msgVer)
                logging.error('Unsupported SNMP version %s' % msgVer)
                return
            reqMsg, wholeMsg = decoder.decode(
                wholeMsg,
                asn1Spec=pMod.Message(),
            )
            print('Notification message from %s:%s: ' %
                  (transportDomain, transportAddress))
            logging.info('Notification message from %s:%s: ' %
                         (transportDomain, transportAddress))
            reqPDU = pMod.apiMessage.getPDU(reqMsg)
            if reqPDU.isSameTypeWith(pMod.TrapPDU()):
                if msgVer == api.protoVersion1:
                    varBinds = pMod.apiTrapPDU.getVarBinds(reqPDU)
                else:
                    varBinds = pMod.apiPDU.getVarBinds(reqPDU)

                print('Var-binds:')
                logging.info(
                    '--------------------------------------------------------------------'
                )
                logging.info('Var-binds:')

                trap = TrapEvent()
                for oid, val in varBinds:
                    print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
                trap.sender = str(transportAddress[0])
                # trap.persistToDB()

        return wholeMsg
    except Exception as e:
        trap = TrapEvent()
        logging.error(str(e))
        trap.persistLogToDB(str(e))
Пример #8
0
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
Пример #9
0
    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)
Пример #10
0
        def cbFun(transportDispatcher, transportDomain, transportAddress,
                  wholeMsg):

            strFname = 'Trap_' + str(
                transportAddress[0]) + '_' + str(port) + '.log'
            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(),
                )
                reqPDU = pMod.apiMessage.getPDU(reqMsg)
                if reqPDU.isSameTypeWith(pMod.TrapPDU()):
                    if msgVer == api.protoVersion1:
                        varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
                    else:
                        varBinds = pMod.apiPDU.getVarBindList(reqPDU)
                    printItNice(varBinds, transportAddress, strFname)

            return wholeMsg
Пример #11
0
    def on_read(self, whole_msg, address, port):
        def oid_to_str(o):
            return ".".join([str(x) for x in o])

        def extract(val):
            def unchain(val):
                c = []
                for i in range(len(val._componentValues)):
                    k = val._componentValues[i]
                    if k is not None:
                        if hasattr(k, "getComponentType"):
                            c.append(k.getComponentType().getNameByPosition(i))
                            c.extend(unchain(k))
                        elif hasattr(k, "_value"):
                            c.append(k._value)
                return c

            v = unchain(val)
            if not v:
                return ""
            v = v[-1]
            if type(v) == tuple:
                return oid_to_str(v)
            return fm_escape(v)

        object = self.map_event(address)
        if not object:
            # Skip events from unknown sources
            return
        if self.log_traps:
            self.logger.debug("SNMP TRAP: %r", whole_msg)
        while whole_msg:
            msg_version = int(api.decodeMessageVersion(whole_msg))
            if api.protoModules.has_key(msg_version):
                p_mod = api.protoModules[msg_version]
            else:
                self.logger.error('Unsupported SNMP version %s from %s',
                                  msg_version, address)
                return
            req_msg, whole_msg = decoder.decode(whole_msg,
                                                asn1Spec=p_mod.Message())
            req_pdu = p_mod.apiMessage.getPDU(req_msg)
            if req_pdu.isSameTypeWith(p_mod.TrapPDU()):
                body = {
                    "source":"SNMP Trap","collector":
                    self.collector_signature
                }
                if msg_version == api.protoVersion1:
                    oid = oid_to_str(p_mod.apiTrapPDU.getEnterprise(req_pdu))
                    body["1.3.6.1.6.3.1.1.4.1.0"] = oid  # snmpTrapOID.0
                    var_binds = p_mod.apiTrapPDU.getVarBindList(req_pdu)
                else:
                    var_binds = p_mod.apiPDU.getVarBindList(req_pdu)
                ts = int(time.time())
                for o, v in var_binds:
                    body[oid_to_str(o._value)] = extract(v)
                if self.log_traps:
                    self.logger.debug("DECODED SNMP TRAP: %s", body)
                self.process_event(ts, object, body)
Пример #12
0
def onTrap(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    # don't even log the trap PDU unless we are at DEBUG level
    if logger.isEnabledFor(logging.DEBUG):
        while wholeMsg:
            msgVer = int(api.decodeMessageVersion(wholeMsg))
            if msgVer in api.protoModules:
                pMod = api.protoModules[msgVer]
            else:
                logger.error('Unsupported SNMP version %s' % msgVer)
                return
            reqMsg, wholeMsg = decoder.decode(
                wholeMsg,
                asn1Spec=pMod.Message(),
            )
            logger.info('Notification message from %s:%s ' %
                        (transportAddress[0], transportAddress[1]))
            reqPDU = pMod.apiMessage.getPDU(reqMsg)
            if reqPDU.isSameTypeWith(pMod.TrapPDU()):
                if msgVer == api.protoVersion1:
                    logger.debug(
                        'Enterprise: %s' %
                        (pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint()))
                    logger.debug(
                        'Agent Address: %s' %
                        (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()))
                    logger.debug(
                        'Generic Trap: %s' %
                        (pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()))
                    logger.debug('Specific Trap: %s' % (
                        pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint()))
                    logger.debug(
                        'Uptime: %s' %
                        (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint()))
                    varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
                else:
                    varBinds = pMod.apiPDU.getVarBindList(reqPDU)
                logger.debug('Var-binds:')
                for oid, val in varBinds:
                    logger.debug('%s = %s' %
                                 (oid.prettyPrint(), val.prettyPrint()))

    # start the 2-stage configuration in a separate thread
    if trapReceiver is not None:
        # execute 2-stage configuration callback if there is one configured in openclos.yaml
        callback = trapReceiver.twoStageConfigurationCallback
        if callback is not None and len(callback) > 0:
            proc = subprocess.Popen(callback, shell=True)
            returnValue = proc.wait()
            if returnValue != 0:
                # 2-stage configuration callback returns non-zero value indicating we SHOULD NOT continue
                logger.debug(
                    'twoStageConfigurationCallback "%s" returns %d, trap ignored'
                    % (callback, returnValue))
                return

        configurator = TwoStageConfigurator(deviceIp=transportAddress[0],
                                            stopEvent=trapReceiver.stopEvent)
        trapReceiver.executor.submit(configurator.start2StageConfiguration)
Пример #13
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    if GlobalVars.END_TRAP_LISTENER==1:
        transportDispatcher.closeDispatcher()
        transportDispatcher.jobFinished(1)
    #print('cbFun is called')
    while wholeMsg:
        #print('loop...')
        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: ' % (
        #    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.getVarBinds(reqPDU)
            else:
                varBinds = pMod.apiPDU.getVarBinds(reqPDU)
            #print('Var-binds:')
            for oid, val in varBinds:
                #print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))                  
                #print(GlobalVars.TRAP_OID)         
                tmpOid=pprint.pformat(oid.prettyPrint())  
                tmpOid='.'+tmpOid.replace("'","")    
                
                if  tmpOid in GlobalVars.TRAP_OID:
                    print("Online Monitoring OutPut:")
                    print('%s=%s' % (oid.prettyPrint(), val.prettyPrint()))
                    
    return wholeMsg
Пример #14
0
    def message_handler(self, transportDispatcher, transportDomain,
                        transportAddress, whole_message):
        while whole_message:
            message_version = api.decodeMessageVersion(whole_message)
            if message_version in api.protoModules:
                protocol = api.protoModules[message_version]
            else:
                self.logger.warn(
                    'Unsupported SNMP version "{}"'.format(message_version))
                return

            request, whole_message = decoder.decode(
                whole_message, asn1Spec=protocol.Message())

            response = protocol.apiMessage.getResponse(request)
            request_pdus = protocol.apiMessage.getPDU(request)
            community = protocol.apiMessage.getCommunity(request)

            if not self.valid_community(community):
                self.logger.warn('Invalid community "{}"'.format(community))
                return

            response_pdus = protocol.apiMessage.getPDU(response)
            var_binds = []
            pending_errors = []
            error_index = 0

            if request_pdus.isSameTypeWith(protocol.GetRequestPDU()):
                for oid, val in protocol.apiPDU.getVarBinds(request_pdus):
                    if oid in self.pdu.oid_mapping:
                        var_binds.append(
                            (oid, self.pdu.oid_mapping[oid].value))
                    else:
                        return
            elif request_pdus.isSameTypeWith(protocol.SetRequestPDU()):
                for oid, val in protocol.apiPDU.getVarBinds(request_pdus):
                    error_index += 1
                    if oid in self.pdu.oid_mapping:
                        self.pdu.oid_mapping[oid].value = val
                        var_binds.append((oid, val))
                    else:
                        var_binds.append((oid, val))
                        pending_errors.append(
                            (protocol.apiPDU.setNoSuchInstanceError,
                             error_index))
            else:
                protocol.apiPDU.setErrorStatus(response_pdus, 'genErr')

            protocol.apiPDU.setVarBinds(response_pdus, var_binds)

            # Commit possible error indices to response PDU
            for f, i in pending_errors:
                f(response_pdus, i)

            transportDispatcher.sendMessage(encoder.encode(response),
                                            transportDomain, transportAddress)

        return whole_message
Пример #15
0
def cbfun(transportDispatcher, transportDomain, transportAddress,
          wholeMsg):  # 处理Trap信息的函数
    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: ' % (transportDomain, transportAddress))  # 打印发送TRAP的源信息

        reqPDU = pMod.apiMessage.getPDU(reqMsg)
        if reqPDU.isSameTypeWith(pMod.TrapPDU()):
            if msgVer == api.protoVersion1:  # SNMPv1的特殊处理方法,可以提取更加详细的信息
                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:  # SNMPv2c的处理方法
                varBinds = pMod.apiPDU.getVarBindList(reqPDU)

            result_dict = {}  # 每一个Trap信息,都会整理返回一个字典

            for x in varBinds:  # 打印详细Trap信息
                result = {}
                for x, y in x.items():
                    # print(x, y.prettyPrint())  # 最原始信息打印
                    # 处理信息到字典
                    if x == 'name':
                        id = y.prettyPrint()  # 把name写入字典的键
                    else:
                        bind_v = [
                            x.strip() for x in y.prettyPrint().split(':')
                        ]
                        for v in bind_v:
                            if v == '_BindValue':
                                next
                            else:
                                result[v.split('=')[0]] = v.split('=')[1]
                result_dict[id] = result

            if analysis(result_dict):  # 把字典传到分析模块进行分析
                print('Notification message from %s:%s: ' %
                      (transportDomain, transportAddress))  # 打印发送TRAP的源信息
                print(analysis(result_dict))

    return wholeMsg
Пример #16
0
    def trap_cb(self, transportDispatcher, transportDomain, transportAddress,
                wholeMsg):

        self.logger.debug('msg=<%s>' % str(wholeMsg))

        msg_strip = wholeMsg.strip()
        self.logger.debug('msg_strip=<%s>' % str(msg_strip))

        if not msg_strip:
            self.logger.warn('warn: msg is an empty <%s>' % str(wholeMsg))
            return

        while wholeMsg:

            msgVer = int(api.decodeMessageVersion(wholeMsg))
            if api.protoModules.has_key(msgVer):
                pMod = api.protoModules[msgVer]
            else:
                self.logger.warn('Unsupported SNMP version %s' % msgVer)
                return
            reqMsg, wholeMsg = decoder.decode(
                wholeMsg,
                asn1Spec=pMod.Message(),
            )
            self.logger.debug('Notification message from %s:%s: ' %
                              (transportDomain, transportAddress))
            reqPDU = pMod.apiMessage.getPDU(reqMsg)
            if reqPDU.isSameTypeWith(pMod.TrapPDU()):
                if msgVer == api.protoVersion1:
                    self.logger.debug(
                        'Enterprise: %s' %
                        (pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint()))
                    self.logger.debug(
                        'Agent Address: %s' %
                        (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()))
                    self.logger.debug(
                        'Generic Trap: %s' %
                        (pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()))
                    trap_num = pMod.apiTrapPDU.getSpecificTrap(
                        reqPDU).prettyPrint()
                    self.logger.debug('Specific Trap: %s' % (trap_num))

                    self.logger.debug(
                        'Uptime: %s' %
                        (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint()))
                    varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
                else:
                    varBinds = pMod.apiPDU.getVarBindList(reqPDU)
                #print 'Var-binds:' , varBinds

                for oid, val in varBinds:
                    self.logger.debug('[%s] = [%s]' %
                                      (oid.prettyPrint(), val.prettyPrint()))
                    msg = val.prettyPrint().split()
                    self.logger.debug('val=%s' % msg)
                    self.interpret_trap(msg, trap_num)
        return wholeMsg
Пример #17
0
    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
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
Пример #19
0
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
Пример #20
0
    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
Пример #21
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    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: ' %
              (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.getVarBinds(reqPDU)
            else:
                varBinds = pMod.apiPDU.getVarBinds(reqPDU)
            print('Var-binds:')

            wework_msg = ''
            for oid, val in varBinds:
                oid = oid.prettyPrint()
                val = val.prettyPrint()
                if val.startswith('0x'):
                    import codecs
                    val = codecs.decode(val[2:], 'hex').decode()
                print('%s = %s' % (oid, val))

                string_valid_oid = get_oid_string(oid)
                string_valid_val = get_val_string(oid, val)
                if string_valid_oid:
                    oid = string_valid_oid
                if string_valid_val:
                    val = string_valid_val
                row_msg = "{}: {}\n".format(oid, val)
                wework_msg += row_msg

            from wework import WeApp
            app = WeApp('container')
            app.send_room_msg(wework_msg)

    return wholeMsg
Пример #22
0
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
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
Пример #24
0
    def _trap_catcher(self, transportDispatcher, transportDomain, transportAddress, wholeMsg):
        """Callback method when a SNMP trap arrives"""
        json_data = {}
        self._trap_name = ""

        while wholeMsg:
            msgVer = int(api.decodeMessageVersion(wholeMsg))
            if msgVer in api.protoModules:
                pMod = api.protoModules[msgVer]
            else:
                self._log_debug(f'Unsupported SNMP version {msgVer}')
                return

            reqMsg, wholeMsg = decoder.decode(
                wholeMsg, asn1Spec=pMod.Message(),)
            self._log_debug(f'Notification message from {transportDomain}:{transportAddress}: ')

            reqPDU = pMod.apiMessage.getPDU(reqMsg)
            if reqPDU.isSameTypeWith(pMod.TrapPDU()):
                if msgVer == api.protoVersion1:
                    self._log_debug(f'Enterprise: {pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint()}')

                    self._log_debug(f'Agent Address: {pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()}')

                    self._log_debug(f'Generic Trap: {pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()}')

                    self._log_debug(f'Specific Trap: {pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint()}')

                    self._log_debug(f'Uptime: {pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint()}')

                    varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
                else:
                    varBinds = pMod.apiPDU.getVarBindList(reqPDU)

                for oid, val in varBinds:
                    nodeDesc, ret_val = self._mib_oid_value(oid, val)

                    # Build up JSON data to be logged in IEM and sent to Halon
                    if nodeDesc != "N/A" and ret_val != "N/A":
                        json_data[nodeDesc] = ret_val

        self._log_debug(f"trap_name: {self._trap_name}")
        self._log_debug(f"enabled_traps: {self._enabled_traps}")

        # Apply filter unless there is an asterisk in the list
        if '*' in self._enabled_traps or \
            self._trap_name in self._enabled_traps:

            # Log IEM
            self._log_iem(json_data)

            # Transmit to Halon
            self._transmit_json_msg(json_data)
Пример #25
0
	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
Пример #26
0
        def cbfun(transportdispatcher, transportdomain, transportaddress,
                  wholemsg):
            t.log("DEBUG", "Entering 'cbfun'\n"+__file__)
            #global results
            global RESPONSE
            while wholemsg:
                msgver = int(api.decodeMessageVersion(wholemsg))
                if msgver in api.protoModules:
                    pmod = api.protoModules[msgver]
                else:
                    RESPONSE += 'Unsupported SNMP version %s' % msgver
                    return
                reqmsg, wholemsg = decoder.decode(
                    wholemsg, asn1Spec=pmod.Message(),
                    )
                RESPONSE += 'Notification message from %s:%s: \n' % (
                    transportdomain, transportaddress
                    )
                reqpdu = pmod.apiMessage.getPDU(reqmsg)
                if msgver == api.protoVersion1:
                    varbinds = pmod.apiTrapPDU.getVarBindList(reqpdu)
                    RESPONSE += 'Var-binds: \n'
                    for oid, val in varbinds:
                        RESPONSE += '%s = %s \n' % (oid.prettyPrint(),
                                                    val.prettyPrint())
                        if pattern_end_trap and re.search(pattern_end_trap,
                                                          RESPONSE, re.I):
                            transportdispatcher.jobFinished(1)
                            RESPONSE += "Stopped trap \n"

                    RESPONSE += 'Enterprise: %s \n' % (
                        pmod.apiTrapPDU.getEnterprise(reqpdu).prettyPrint()
                        )

                    RESPONSE += 'Agent Address: %s \n' % (
                        pmod.apiTrapPDU.getAgentAddr(reqpdu).prettyPrint()
                        )
                    RESPONSE += 'Generic Trap: %s \n' % (
                        pmod.apiTrapPDU.getGenericTrap(
                            reqpdu).prettyPrint())

                    RESPONSE += 'Specific Trap: %s \n' % (
                        pmod.apiTrapPDU.getSpecificTrap(
                            reqpdu).prettyPrint()
                        )

                    RESPONSE += 'Uptime: %s \n' % (
                        pmod.apiTrapPDU.getTimeStamp(
                            reqpdu).prettyPrint()
                        )
                else:
                    varbinds = pmod.apiPDU.getVarBindList(reqpdu)
Пример #27
0
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
Пример #28
0
    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)
Пример #29
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    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 ' %
              (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)

            result_dict = {}
            for x in varBinds:
                result = {}
                for x, y in x.items():
                    # print(x, y)
                    if x == 'name':
                        id = y.prettyPrint()
                    else:
                        bind_v = [
                            x.strip() for x in y.prettyPrint().split(':')
                        ]
                        print(bind_v)
                        for v in bind_v:
                            if v == '_BindValue':
                                next
                            else:
                                result[v.split('=')[0]] = v.split('=')[1]
                result_dict[id] = result
            analysis(result_dict)
    return wholeMsg
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        
Пример #31
0
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" % rlookup((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        
Пример #32
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    while wholeMsg:
        msgVer = int(api.decodeMessageVersion(wholeMsg))
        if msgVer in api.protoModules:
            print('supported SNMP version %s' % 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()))
                #import pdb
                #pdb.set_trace()
                varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
            else:
                varBinds = pMod.apiPDU.getVarBindList(reqPDU)
            print('Var-binds:')

            result = []
            import pdb
            pdb.set_trace()
            for val in varBinds:
                val_dict = {}
                for line in val.prettyPrint().split('\n'):
                    key_value = line.split('=')
                    if len(key_value) != 2:
                        continue
                    val_dict[key_value[0].strip()] = key_value[1].strip()
                    result.append(val_dict)
            #print('%s = %s' % (oid, val))
            print("-----------")
            print(result)
    return wholeMsg
    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

        # Stop the receiver if the trap we are looking for was received.
        if trap_filter(domain, sock, pdu):
            transport.jobFinished(1)
Пример #34
0
 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)
Пример #35
0
    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")
Пример #36
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    global numOfModems
    print('cbFun is called')
    while wholeMsg:
        print('loop...')
        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: ' %
              (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.getVarBinds(reqPDU)
            #print('Var-binds:')
            message = ""
            for oid, val in varBinds:
                #print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
                message = val.prettyPrint(
                )  # ignoring past values, thus saving the last value - the snmptrap message itself

            print('%s \n' % message)
            if "is now available" in message:
                # welcome new modem
                numOfModems = numOfModems + 1
            if "is dead" in message:
                print("modem died")
                # how unfortunate... you will always be remembered, there are no modems like you "modem_NO_X"
                # getting you back to life(?)
    return wholeMsg
Пример #37
0
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)
Пример #38
0
    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)
Пример #39
0
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
Пример #40
0
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)
Пример #41
0
 def cbFun(self, transportDispatcher, transportDomain, transportAddress, wholeMsg):
     mibInstr = self._mibInstr
     mibInstrIdx = self._mibInstrIdx
     while wholeMsg:
         msgVer = api.decodeMessageVersion(wholeMsg)
         if msgVer in api.protoModules:
             pMod = api.protoModules[msgVer]
         else:
             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
         # GETNEXT PDU
         if reqPDU.isSameTypeWith(pMod.GetNextRequestPDU()):
             # Produce response var-binds
             errorIndex = -1
             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
                     pMod.apiPDU.setEndOfMibError(rspPDU, 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
                     try:
                         pMod.apiPDU.setNoSuchInstanceError(rspPDU, errorIndex)
                     except IndexError:
                         pass
                     varBinds = pMod.apiPDU.getVarBinds(reqPDU)
                     break
         else:
             # Report unsupported request type
             pMod.apiPDU.setErrorStatus(rspPDU, "genErr")
         pMod.apiPDU.setVarBinds(rspPDU, varBinds)
         transportDispatcher.sendMessage(encoder.encode(rspMsg), transportDomain, transportAddress)
     return wholeMsg
Пример #42
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    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: ' %
              (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:
                a = oid.prettyPrint().strip()
                b = val.prettyPrint().strip().split('\n')
                print(a)

                for line in b:
                    item = line.strip()
                    if item.startswith('string-value'):
                        print(
                            'string-value=' +
                            item.replace('string-value=0x', '').decode('hex'))

                    else:
                        print(item)

    return wholeMsg
Пример #43
0
def snmpRecvCallback(dispatcher, domain, address, msg):
    logger = logging.getLogger("apctrap")
    while msg:
        version = int(api.decodeMessageVersion(msg))
        if version in api.protoModules: module = api.protoModules[version]
        else:
            logger.error("SYSTEM\tERROR | Unsupported SNMP Version")
            return

        req, msg = decoder.decode(msg, asn1Spec=module.Message())
        logger.info("NOTIFICATION\t{} | {}".format(address, domain))

        pdu = module.apiMessage.getPDU(req)
        if not pdu.isSameTypeWith(module.TrapPDU()): continue

        if version == api.protoVersion1:
            varBinds = module.apiTrapPDU.getVarBindList(pdu)
        else:
            varBinds = module.apiPDU.getVarBindList(pdu)

        for v, b in varBinds:
            key = '.'.join([str(i) for i in v._value])
            value = b.getComponent('simple')._value

            parsed = ObjectType(ObjectIdentity(key), value)
            try:
                parsed.resolveWithMib(viewController)
            except Exception as e:
                logger.warning(
                    "TRAP\tERROR | Failed to resolve symbol ({}={})".format(
                        key, value))
                continue
            key, value = parsed.prettyPrint().split(" = ")
            logger.info("TRAP\t{} | {}".format(key, value))

            if key == "PowerNet-MIB::mtrapargsString.0":
                message = value
                for contact in contacts['contacts']:
                    phoneNumber = contact['phoneNumber']
                    _redis.publish(
                        'sms',
                        json.dumps(
                            dict(phoneNumber=phoneNumber, message=message)))

    return msg
Пример #44
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):#处理Trap信息的函数
    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: ' % (
            transportDomain, transportAddress#打印发送TRAP的源信息
            )
        )
        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()))#打印具体的Trap信息内容
    return wholeMsg
Пример #45
0
    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):
            raise StopListener()


        # Stop the receiver if the trap we are looking for was received.
        if False:
            raise StopListener()
Пример #46
0
    def _callback(self, transport_dispatcher, transport_domain, transport_address, whole_msg):
        try:
            while whole_msg:
                msg_version = int(api.decodeMessageVersion(whole_msg))
                if msg_version not in api.protoModules:
                    logging.info('Unsupported SNMP version {} {}'.format(msg_version, transport_address[0]))
                    return

                proto_module = api.protoModules[msg_version]

                request_msg, whole_msg = decoder.decode(whole_msg, asn1Spec=proto_module.Message(),)
                request_pdu = proto_module.apiMessage.getPDU(request_msg)
                if transport_address[0] == '0.0.0.0':
                    logging.info('Broadcast snmptrap ignored')
                    return
                if request_pdu.isSameTypeWith(proto_module.TrapPDU()):
                    self._extract_and_process_trap(proto_module, request_pdu, transport_address)
        except Exception as exc:
            logging.error('Error snmptrap: {}  {}'.format(exc, exc.__class__.__name__))
Пример #47
0
    def callback_func(self, transport_dispatcher, transport_domain,
                      transport_address, whole_msg):
        while whole_msg:
            msg_ver = int(snmp_api.decodeMessageVersion(whole_msg))
            if msg_ver in snmp_api.protoModules:
                p_mod = snmp_api.protoModules[msg_ver]
            else:
                LOG.error('Unsupported SNMP version %s.' % msg_ver)
                return
            req_msg, whole_msg = decoder.decode(
                whole_msg, asn1Spec=p_mod.Message(),
            )
            req_pdu = p_mod.apiMessage.getPDU(req_msg)
            if req_pdu.isSameTypeWith(p_mod.TrapPDU()):
                ver_binds = p_mod.apiTrapPDU.getVarBinds(req_pdu) \
                    if msg_ver == snmp_api.protoVersion1 \
                    else p_mod.apiPDU.getVarBinds(req_pdu)

                binds_dict = self._convert_binds_to_dict(ver_binds)
                LOG.debug('Receive binds info after convert: %s' % binds_dict)
                self._send_snmp_to_queue(binds_dict)
Пример #48
0
def processtrapmsg(wholeMsg):
    """
    check the snmp version of the message 
    if supported version(version in [1,2,3]) process the message
    get version,community and data pdus
    get all the pdus (snmpV2-trap,requestid, errorstatus ,error index and varBindings)
    break varBindings into oid value pair
    """
    msgDict = {}

    try:

        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(),
        )
        reqPDU = pMod.apiMessage.getPDU(reqMsg)

        for key, value in reqPDU.items():
            msgDict[str(key)] = str(value)
        msgDict.pop("variable-bindings")

        varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
        bindDict = {}
        for x in varBinds:
            y = str(x[1])
            start_value = y.find(start)
            bindDict[str(x[0])] = y[start_value + start_len:y.find(end)]
        msgDict.update(bindDict)
    except Exception as e:
        print(e)
    return (msgDict)
Пример #49
0
    def _cbHandler(self, transportDispatcher, transportDomain, \
                  transportAddress, wholeMsg):
        '''
        ' 回调处理接收信息
        ' raise Exception: trap消息处理失败时抛出
        '''
        logger.info('enter the _cbHandler function')
        while wholeMsg:
            # 提取为checkVersion, 返回pMod
            msgVer = api.decodeMessageVersion(wholeMsg)
            if msgVer in api.protoModules:
                pMod = api.protoModules[msgVer]
            else:
                return
            reqMsg, wholeMsg = decoder.decode(
                wholeMsg, asn1Spec=pMod.Message(),
                )
            reqPDU = pMod.apiMessage.getPDU(reqMsg)

            if reqPDU.isSameTypeWith(pMod.TrapPDU()):
                # 获取绑定值
                if msgVer == api.protoVersion1:
                    agentip = pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()
                    varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
                else:
                    agentip = transportAddress[0]
                    varBinds = pMod.apiPDU.getVarBindList(reqPDU)
                    
            try:
                # 构造处理器处理trap消息
                handler = HandlerFactory.createHandler(agentip, varBinds, self._configdata)
                if not handler is None:
                    logger.info('begin handler the trap')
                    handler.handle()
                else:
                    logger.info("do not surpport the alarm ")
            except Exception, err:
                print err
                logger.info("handle the host[%s] alarm exception[%s]" % (agentip, err))
Пример #50
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):

    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: ' %
              (transportDomain, transportAddress))
        reqPDU = pMod.apiMessage.getPDU(reqMsg)
        if reqPDU.isSameTypeWith(pMod.TrapPDU()):
            varBinds = pMod.apiPDU.getVarBindList(reqPDU)
            #print('Var-binds:')
    GetTrapData(varBinds)

    return wholeMsg
Пример #51
0
def snmpRecvCallback(dispatcher, domain, address, msg):
    logger=logging.getLogger("apctrap")
    while msg:
        version=int(api.decodeMessageVersion(msg))
        if version in api.protoModules: module=api.protoModules[version]
        else:
            logger.error("SYSTEM\tERROR | Unsupported SNMP Version")
            return

        req,msg=decoder.decode(msg, asn1Spec=module.Message())
        logger.info("NOTIFICATION\t{} | {}".format(address, domain))

        pdu=module.apiMessage.getPDU(req)
        if not pdu.isSameTypeWith(module.TrapPDU()): continue

        if version==api.protoVersion1:
            varBinds=module.apiTrapPDU.getVarBindList(pdu)
        else: varBinds=module.apiPDU.getVarBindList(pdu)

        for v,b in varBinds:
            key='.'.join([str(i) for i in v._value])
            value=b.getComponent('simple')._value

            parsed=ObjectType(ObjectIdentity(key), value)
            try: parsed.resolveWithMib(viewController)
            except Exception as e: 
                logger.warning("TRAP\tERROR | Failed to resolve symbol ({}={})".format(key,value))
                continue
            key,value=parsed.prettyPrint().split(" = ")
            logger.info("TRAP\t{} | {}".format(key,value))

            if key=="PowerNet-MIB::mtrapargsString.0":
                message=value
                for contact in contacts['contacts']:
                    phoneNumber=contact['phoneNumber']
                    _redis.publish('sms', json.dumps(dict(phoneNumber=phoneNumber, message=message)))

    return msg
Пример #52
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    
    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: ' % (
            transportDomain, transportAddress
            )
        )
        reqPDU = pMod.apiMessage.getPDU(reqMsg)
        if reqPDU.isSameTypeWith(pMod.TrapPDU()):
            varBinds = pMod.apiPDU.getVarBindList(reqPDU)
            #print('Var-binds:')
    GetTrapData(varBinds)

    return wholeMsg
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):

    while wholeMsg:
        msgVer = int(api.decodeMessageVersion(wholeMsg))
        if msgVer in api.PROTOCOL_MODULES:
            pMod = api.PROTOCOL_MODULES[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.SNMP_VERSION_1:
                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.getVarBinds(reqPDU)

            else:
                varBinds = pMod.apiPDU.getVarBinds(reqPDU)

            print('Var-binds:')

            for oid, val in varBinds:
                print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))

    return wholeMsg
def trapCallback(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    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)
        
        splunkevent =""
        
        if reqPDU.isSameTypeWith(pMod.TrapPDU()):
            if msgVer == api.protoVersion1:
                
                #splunkevent += 'notification_from_domain = "%s" ' % (transportDomain)
                #splunkevent += 'notification_from_address = "%s" ' % (transportAddress)               
                splunkevent += 'notification_enterprise = "%s" ' % (pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint())
                splunkevent += 'notification_agent_address = "%s" ' % (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint())
                splunkevent += 'notification_generic_trap = "%s" ' % (pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint())
                splunkevent += 'notification_specific_trap = "%s" ' % (pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint())
                splunkevent += 'notification_uptime = "%s" ' % (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint())
                
                varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
            else:
                varBinds = pMod.apiPDU.getVarBindList(reqPDU)
            for oid, val in varBinds:
                splunkevent +='%s = "%s" ' % (oid.prettyPrint(), val.prettyPrint())
        
        if splunkevent != "":
            print_xml_single_instance_mode(splunkevent)
            sys.stdout.flush() 
                
    return wholeMsg        
Пример #55
0
    def _call(self, transport_dispatcher, transport_domain, transport_address, whole_msg):
        if not whole_msg:
            return

        msg_version = int(api.decodeMessageVersion(whole_msg))

        if msg_version in api.protoModules:
            proto_module = api.protoModules[msg_version]
        else:
            stats.incr("unsupported-notification", 1)
            logging.error("Unsupported SNMP version %s", msg_version)
            return

        host = transport_address[0]
        version = SNMP_VERSIONS[msg_version]

        try:
            req_msg, whole_msg = decoder.decode(whole_msg, asn1Spec=proto_module.Message(),)
        except (ProtocolError, ValueConstraintError) as err:
            stats.incr("unsupported-notification", 1)
            logging.warning("Failed to receive trap (%s) from %s: %s", version, host, err)
            return
        req_pdu = proto_module.apiMessage.getPDU(req_msg)

        community = proto_module.apiMessage.getCommunity(req_msg)
        if self.community and community != self.community:
            stats.incr("unauthenticated-notification", 1)
            logging.warning("Received trap from %s with invalid community: %s... discarding", host, community)
            return

        if not req_pdu.isSameTypeWith(proto_module.TrapPDU()):
            stats.incr("unsupported-notification", 1)
            logging.warning("Received non-trap notification from %s", host)
            return

        if msg_version not in (api.protoVersion1, api.protoVersion2c):
            stats.incr("unsupported-notification", 1)
            logging.warning("Received trap not in v1 or v2c")
            return

        trap = Notification.from_pdu(host, proto_module, version, req_pdu)
        if trap is None:
            stats.incr("unsupported-notification", 1)
            logging.warning("Invalid trap from %s: %s", host, req_pdu)
            return

        dde = DdeNotification(trap, self.config.handlers[trap.oid])
        dde_run(dde)
        handler = dde.handler

        trap.severity = handler["severity"]
        trap.manager = self.hostname

        if handler.get("expiration", None):
            expires = parse_time_string(handler["expiration"])
            expires = timedelta(**expires)
            trap.expires = trap.sent + expires

        stats.incr("traps_received", 1)
        objid = ObjectId(trap.oid)
        if handler.get("blackhole", False):
            stats.incr("traps_blackholed", 1)
            logging.debug("Blackholed %s from %s", objid.name, host)
            return

        logging.info("Trap Received (%s) from %s", objid.name, host)
        stats.incr("traps_accepted", 1)


        duplicate = False
        try:
            stats.incr("db_write_attempted", 1)
            self.conn.add(trap)
            self.conn.commit()
            stats.incr("db_write_successful", 1)
        except OperationalError as err:
            self.conn.rollback()
            logging.warning("Failed to commit: %s", err)
            stats.incr("db_write_failed", 1)
            # TODO(gary) reread config and reconnect to database
        except InvalidRequestError as err:
            # If we get into this state we should rollback any pending changes.
            stats.incr("db_write_failed", 1)
            self.conn.rollback()
            logging.warning("Bad state, rolling back transaction: %s", err)
        except IntegrityError as err:
            stats.incr("db_write_duplicate", 1)
            duplicate = True
            self.conn.rollback()
            logging.info("Duplicate Trap (%s) from %s. Likely inserted by another manager.", objid.name, host)
            logging.debug(err)

        self._send_mail(handler, trap, duplicate)
Пример #56
0
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    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 ' % (transportAddress[0], transportAddress[1]))
        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)
            notify_msg = {}
            #los varbinds vienen el tuplas de tuplas ((val1, val2),(val1, val2))
            cli = HttpHelper(server_addr=SERVER_IP, server_port=int(SERVER_PORT))
            uptime = int(varBinds[0][1].getComponent(True).prettyPrint()) / 100
            notify_type = get_OID_Name(varBinds[1][1].getComponent(True).prettyPrint())
            notify_msg['direccion'] = transportAddress[0]
            # Verificar si ya existe en la BD
            gres = json.loads(dweb.do_get(url="/api/network/nodes/?ip=" + transportAddress[0]))
            print gres[0]["pos"]
            #gres = dweb.do_get(url="/api/network/nodes/?ip=" + transportAddress[0])
            if len(gres)>0:
                DB_ID = gres[0]["id"]
            #else:
                # DB_ID = int(gres[0]["id"])
                #DB_ID = int(gres.split(',')[0].split(':')[1])
            #notify_msg['uptime'] = uptime
            #notify_msg['tipo'] = notify_type
            if notify_type == "nsNotifyShutdown":
                print("NOTIFICAR DE APAGADO")
                #http_post(notify_msg, "/gestion/boot_event/agregar/")
                notification = transportAddress[0] + " ("+ gres[0]["pos"]+") se ha apago el " + time.strftime(
                    "%d-%m-%Y a las %H:%M")
                notification2 = transportAddress[0] + " (" + gres[0]["pos"] + ") se esta apagando"

                dweb.do_post(url="/api/network/notification/", data={'description': notification, 'node': DB_ID})
                cli.http_post(url="/shutdown", data={'description': notification2, 'node': DB_ID})

                #print (notify_msg)
            elif notify_type == "coldStart":
                print("NOTIFICAR DE ARRANQUE")
                #http_post(notify_msg, "/gestion/boot_event/agregar/")
                notification = transportAddress[0] + " (" + gres[0]["pos"] + ") se encedio el " + time.strftime(
                    "%d-%m-%Y a las %H:%M")
                notification2 = transportAddress[0] + " (" + gres[0]["pos"] + ") esta iniciando"

                dweb.do_post(url="/api/network/notification/", data={'description': notification, 'node': DB_ID})
                cli.http_post(url="/startup", data={'description': notification2, 'node': DB_ID})
                #print (notify_msg)
            elif notify_type == "linkUp":
                #6 varBinds pos 3,4,5 = interfaceIndex, adminStatus, operstatus
                #print("NOTIFICAR DE INTERFACE UP")
                if_desc = '1.3.6.1.2.1.2.2.1.2.'+varBinds[2][1].getComponent(True).prettyPrint()
                #admin_stat = '1.3.6.1.2.1.2.2.1.7.'+varBinds[2][1].getComponent(True).prettyPrint()
                #oper_stat = '1.3.6.1.2.1.2.2.1.8.'+varBinds[2][1].getComponent(True).prettyPrint()
                iface = get_request(destino=transportAddress[0], mib_oid=if_desc)
                oper = varBinds[3][1].getComponent(True).prettyPrint()
                admin = varBinds[4][1].getComponent(True).prettyPrint()
                notify_msg['nombre'] = iface
                notify_msg['estado_operacional'] = OPER_STATUS[int(oper)]
                notify_msg['estado_administrativo'] = OPER_STATUS[int(admin)]
                #http_post(notify_msg, "/gestion/interface_event/agregar/")
                cli.http_post(url="/linkup", data=notify_msg)
                #print(notify_msg)
                #target = open('error.log', 'w')
                #target.write(res.text)
                #target.close()
            elif notify_type == "linkDown":
                #6 varBinds pos 3,4,5 = interfaceIndex, adminStatus, operstatus
                print("NOTIFICAR DE INTERFACE DOWN")
                if_desc = '1.3.6.1.2.1.2.2.1.2.'+varBinds[2][1].getComponent(True).prettyPrint()
                iface = get_request(destino=transportAddress[0], mib_oid=if_desc)
                oper = varBinds[3][1].getComponent(True).prettyPrint()
                admin = varBinds[4][1].getComponent(True).prettyPrint()
                notify_msg['nombre'] = iface
                notify_msg['estado_operacional'] = OPER_STATUS[int(oper)]
                notify_msg['estado_administrativo'] = OPER_STATUS[int(admin)]
                #http_post(notify_msg, "/gestion/interface_event/agregar/")
                #cli.http_post(url="/gestion/interface_event/agregar/", data=notify_msg)
                cli.http_post(url="/linkdown", data=notify_msg)
                #print(notify_msg)
            elif notify_type == "mteTriggerFired":
                pass
                """9 varBinds
                3 = The name of the trigger causing the notification.
                7 =The value of the object at mteTriggerValueID when a trigger fired.
                8 = The process name we're counting/checking on.
                9 = The reason for the failure
                """
                #print("NOTIFICAR De DISMAN")
                #notify_msg['tabla'] = varBinds[2][1].getComponent(True).prettyPrint()
                #notify_msg['warning'] = (varBinds[6][1].getComponent(True).prettyPrint())
                #notify_msg['item'] = (varBinds[7][1].getComponent(True).prettyPrint())
                #notify_msg['mensaje'] = (varBinds[8][1].getComponent(True).prettyPrint())
                #http_post(notify_msg, "/gestion/general_event/agregar/")
                #cli.http_post(url="/gestion/general_event/agregar/", data=notify_msg)
                #print(notify_msg)

            #print(notify_msg)

            """
            for oid, val in varBinds:
                print("----------------------------------")
                print get_OID_Name(oid.prettyPrint()) + ":"
                if get_OID_Name(oid.prettyPrint()) == "sysUpTime":
                    uptime = int(val.getComponent(True).prettyPrint()) / 100
                    print("Uptime:" + str(uptime))
                elif get_OID_Name(oid.prettyPrint()) == "snmpTrapOID":
                    valor = get_OID_Name(val.getComponent(True).prettyPrint())
                    #if aceptable_value(valor):
                    print get_OID_Name(val.getComponent(True).prettyPrint()) +":"
                    #else:
                        #print("No me interesa")
                elif get_OID_Name(oid.prettyPrint()) == "snmpTrapEnterprise":
                    print get_OID_Name(val.getComponent(True).prettyPrint())
                else:
                    print val.getComponent(True).prettyPrint()
            """

    return wholeMsg
def bandwidth_monitor_activator(transportDispatcher, transportDomain,transportAddress, wholeMsg):
    global agentaddress, trapname, ifindex, ifspeed    
  
    # SNMP Trap receiver- listens to IPASO clients for SNMP trap notifications
    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: ' % (
	    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()
		    )
		)
		agentaddress = (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint())
		print('Generic Trap: %s' % (
		    pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()
		    )
		)
		trapname = 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)
		
	    # Received trap from IPASO
            #Note:(Modify below linkUp trapname with actual ipaso bw_change trapname in NEC setup)
	    elif trapname == '\'linkUp\'':
		varBinds = pMod.apiPDU.getVarBindList(reqPDU)
		data = (varBinds.getComponentByPosition(5).getComponentByPosition(1)
                .getComponentByPosition(0).getComponentByPosition(1))
		ifspeed = data.getComponentByPosition(5)
		#print('%s = %s' % (oid.prettyPrint(),val.prettyPrint()))
		print 'Received IPASO BW Change snmp trap to: ', ifspeed
		if (IPASO_IP == agentaddress) and (trapname == '\'linkUp\''):
		      
		    # Vaidate remote JET IP, incoming interface and modify LSP BW
                    # If IPASO Bandwidth is greaterthan 200Mbps then    
		    if ifspeed >= 200000000:
		    
			# Validate REMOTE_JET_ROUTE_ADDRESS is reachable via IPASO_IF
            xml_query = "<get-route-information><destination>%s/destination><extensive/></get-route-information>" %REMOTE_JET_ROUTE_ADDRESS
            op_command = OperationCommand(xml_query, in_format=OperationFormatType.OPERATION_FORMAT_XML,
                                            out_format=OperationFormatType.OPERATION_FORMAT_XML);
			result1 = mgmt_handle.ExecuteOpCommand(op_comand)   
			intf1 = re.search (r"<via>(\D+-\d+/\d+/\d+\.\d+)", result1)
			if intf1:
			    print ('Collected IPASO connected interface name is:',
                            intf1.group(1))
			    destination_intf = intf1.group(1)
			    if destination_intf == IPASO_IF:
				print ('Discovered interface matches IPASO connected'
                                'interface')
                xml_query = "<get-mpls-lsp-information><extensive/><regex>lsp1</regex></get-mpls-lsp-information>"
                op_command = OperationCommand(xml_query, in_format=OperationFormatType.OPERATION_FORMAT_XML,
                                            out_format=OperationFormatType.OPERATION_FORMAT_XML);
				result2 = mgmt_handle2.ExecuteOpCommand(op_command)   
				rbw = re.search (r"<bandwidth>(\d+Mbps)<", result2)
				if rbw:
				    print ('Existing remote jet router lsp bandwidth'
                                    'is:', rbw.group(1))
				    rlspbw = rbw.group(1)
				    if rlspbw != '200Mbps':
				    
				# Modify MPLS LSP bandwidth
                    config = ConfigLoadCommit(lsp_bw_change,ConfigFormatType.CONFIG_FORMAT_SET, ConfigDatabaseType.CONFIG_DB_SHARED,
                              ConfigLoadType.CONFIG_LOAD_REPLACE, commit)
					result3 = mgmt_handle2.ExecuteCfgCommand(config)
					print ('Modified remote JET router MPLS' 
                                        'lsp bandwidth to 200 mbps \n')
Пример #58
0
def callback(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    while wholeMsg:
        LOG.debug('Notification message from %(domain)s:%(address)s: ',
                  {'domain': transportDomain, 'address': transportAddress})

        msgVer = int(api.decodeMessageVersion(wholeMsg))
        if msgVer in api.protoModules:
            pMod = api.protoModules[msgVer]
        else:
            LOG.warning('Unsupported SNMP version %(version)s in message from '
                        '%(domain)s:%(address)s',
                        {'version': msgVer, 'domain': transportDomain,
                         'address': transportAddress})
            return
        reqMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())
        reqPDU = pMod.apiMessage.getPDU(reqMsg)
        if reqPDU.isSameTypeWith(pMod.TrapPDU()):
            if msgVer == api.protoVersion1:
                enterprise = pMod.apiTrapPDU.getEnterprise(reqPDU)
                if enterprise.asTuple() != _PET_ENTERPRISE_OID:
                    LOG.warning('Not a PET trap in message from '
                                '%(domain)s:%(address)s',
                                {'domain': transportDomain,
                                 'address': transportAddress})
                    return

                agent_addr = pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()
                LOG.debug('Agent address is %s', agent_addr)

                specific_trap = int(pMod.apiTrapPDU.getSpecificTrap(reqPDU))

                varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
                oct_values = None
                for oid, val in varBinds:
                    if oid == _PET_BINDING_OID:
                        try:
                            oct_values = val['simple']['string'].asOctets()
                        except error.PyAsn1Error:
                            pass

                if oct_values is None:
                    LOG.error('Invalid trap variables in message from '
                              '%(domain)s:%(address)s',
                              {'domain': transportDomain,
                               'address': transportAddress})
                    return

                try:
                    parsed_trap = pet.parse_specific_trap(specific_trap)
                    bindings = pet.parse_pet_values(oct_values)
                except exception.PETProxyException as e:
                    LOG.error('Error in message from %(domain)s:%(address)s: '
                              '%(error)s',
                              {'domain': transportDomain,
                               'address': transportAddress,
                               'error': e})
                    return

                _send_notification(parsed_trap, bindings)

            else:
                # not supported by PET spec
                LOG.warning('Only SNMP version 1 is supported by PET, '
                            '%(version)s in message from '
                            '%(domain)s:%(address)s',
                            {'version': msgVer, 'domain': transportDomain,
                             'address': transportAddress})

    return wholeMsg
Пример #59
0
    def commandResponderCbFun(transportDispatcher, transportDomain,
                              transportAddress, wholeMsg):
        while wholeMsg:
            msgVer = api.decodeMessageVersion(wholeMsg)
            if msgVer in api.protoModules:
                pMod = api.protoModules[msgVer]
            else:
                sys.stdout.write('Unsupported SNMP version %s\r\n' % (msgVer,))
                return
            reqMsg, wholeMsg = decoder.decode(
                wholeMsg, asn1Spec=pMod.Message(),
                )

            communityName = reqMsg.getComponentByPosition(1)
            for communityName in probeContext(transportDomain, transportAddress, communityName):
                if communityName in contexts:
                    break
            else:
                return wholeMsg
            
            rspMsg = pMod.apiMessage.getResponse(reqMsg)
            rspPDU = pMod.apiMessage.getPDU(rspMsg)        
            reqPDU = pMod.apiMessage.getPDU(reqMsg)
    
            if reqPDU.isSameTypeWith(pMod.GetRequestPDU()):
                backendFun = contexts[communityName].readVars
            elif reqPDU.isSameTypeWith(pMod.SetRequestPDU()):
                backendFun = contexts[communityName].writeVars
            elif reqPDU.isSameTypeWith(pMod.GetNextRequestPDU()):
                backendFun = contexts[communityName].readNextVars
            elif hasattr(pMod, 'GetBulkRequestPDU') and \
                     reqPDU.isSameTypeWith(pMod.GetBulkRequestPDU()):
                if not msgVer:
                    sys.stdout.write('GETBULK over SNMPv1 from %s:%s\r\n' % (
                        transportDomain, transportAddress
                        ))
                    return wholeMsg
                backendFun = lambda varBinds: getBulkHandler(varBinds,
                    pMod.apiBulkPDU.getNonRepeaters(reqPDU),
                    pMod.apiBulkPDU.getMaxRepetitions(reqPDU),
                    contexts[communityName].readNextVars)
            else:
                sys.stdout.write('Unsuppored PDU type %s from %s:%s\r\n' % (
                    reqPDU.__class__.__name__, transportDomain,
                    transportAddress
                    ))
                return wholeMsg
    
            varBinds = backendFun(
                pMod.apiPDU.getVarBinds(reqPDU)
                )

            # Poor man's v2c->v1 translation
            errorMap = {  rfc1902.Counter64.tagSet: 5,
                          rfc1905.NoSuchObject.tagSet: 2,
                          rfc1905.NoSuchInstance.tagSet: 2,
                          rfc1905.EndOfMibView.tagSet: 2  }
 
            if not msgVer:
                for idx in range(len(varBinds)):
                    oid, val = varBinds[idx]
                    if val.tagSet in errorMap:
                        varBinds = pMod.apiPDU.getVarBinds(reqPDU)
                        pMod.apiPDU.setErrorStatus(rspPDU, errorMap[val.tagSet])
                        pMod.apiPDU.setErrorIndex(rspPDU, idx+1)
                        break

            pMod.apiPDU.setVarBinds(rspPDU, varBinds)
            
            transportDispatcher.sendMessage(
                encoder.encode(rspMsg), transportDomain, transportAddress
                )
            
        return wholeMsg
def bandwidth_monitor_activator(transportDispatcher, transportDomain,transportAddress, wholeMsg):
	"""
	SNMP TRAP Receiver PURE PYTHON CODE
	"""
	global agentaddress, trapname, ifindex, ifspeed    
	# SNMP Trap receiver- listens to IPASO clients for SNMP trap notifications
	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: ' % (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()
					)
					)
				agentaddress = (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint())
				print('Generic Trap: %s' % (
					pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()
					)
					)
				trapname = 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)

			# Received trap from IPASO
			#Note:(Modify below linkUp trapname with actual ipaso bw_change trapname in NEC setup)
			elif trapname == '\'linkUp\'':
				varBinds = pMod.apiPDU.getVarBindList(reqPDU)
				data = (varBinds.getComponentByPosition(5).getComponentByPosition(1)
							.getComponentByPosition(0).getComponentByPosition(1))
				ifspeed = data.getComponentByPosition(5)
				print 'Received IPASO BW Change snmp trap to: ', ifspeed
				if (IPASO_IP == agentaddress) and (trapname == '\'linkUp\''):
					# Vaidate remote JET IP, incoming interface and modify LSP BW
					# If IPASO Bandwidth is greaterthan 200Mbps then    
					if ifspeed >= 200000000:
						# Validate REMOTE_JET_ROUTE_ADDRESS is reachable via IPASO_IF
						xml_query = "<get-route-information><destination>%s/destination><extensive/></get-route-information>" %REMOTE_JET_ROUTE_ADDRESS
						op_command = mgd_service_pb2.ExecuteOpCommandRequest(request_id=2,
																				xml_command=xml_query,
																				out_format=mgd_service_pb2.OPERATION_FORMAT_XML)
						command_result = mgmt_stub.ExecuteOpCommand(op_command)
						result1 = _get_data(command_result, 2)
						
						intf1 = re.search (r"<via>(\D+-\d+/\d+/\d+\.\d+)", result1)
						if intf1:
							print ('Collected IPASO connected interface name is:',
							intf1.group(1))
							destination_intf = intf1.group(1)
							if destination_intf == IPASO_IF:
								print ('Discovered interface matches IPASO connected'
								'interface')
								xml_query = "<get-mpls-lsp-information><extensive/><regex>lsp1</regex></get-mpls-lsp-information>"
								op_command = mgd_service_pb2.ExecuteOpCommandRequest(request_id=3,
																					xml_command=xml_query,
																					out_format=mgd_service_pb2.OPERATION_FORMAT_XML)
								command_result = mgmt_stub2.ExecuteOpCommand(op_command)
								result2 = _get_data(command_result, 3)
								rbw = re.search (r"<bandwidth>(\d+Mbps)<", result2)
								if rbw:
									print ('Existing remote jet router lsp bandwidth'
													'is:', rbw.group(1))
									rlspbw = rbw.group(1)
									if rlspbw != '200Mbps':
										# Modify MPLS LSP bandwidth
										config_commit = mgd_service_pb2.ConfigCommit(commit_type=mgd_service_pb2.CONFIG_COMMIT,
																						comment="setting mpls bandwidth")
										config = ExecuteCfgCommandRequest(request_id=4,
																			xml_config=lsp_bw_change,
																			load_type=mgd_service_pb2.CONFIG_LOAD_MERGE,
																			commit=config_commit)
										result3 = mgmt_stub2.ExecuteCfgCommand(config)
										if result3.status == mgd_service_pb2.SUCCESS:
											print ('Modified remote JET router MPLS' 
															'lsp bandwidth to 200 mbps \n')
										else:
											print result3.message
									else:
										print ('Bandwidth configs exists in remote'
															'jet router hence No changes required \n')
								else:
									config_commit = mgd_service_pb2.ConfigCommit(commit_type=mgd_service_pb2.CONFIG_COMMIT,
																					comment="setting mpls bandwidth")
									config = ExecuteCfgCommandRequest(request_id=4,
																		xml_config=lsp_bw_change,
																		load_type=mgd_service_pb2.CONFIG_LOAD_MERGE,
																		commit=config_commit)
									result3 = mgmt_stub2.ExecuteCfgCommand(config)
									if result3.status != mgd_service_pb2.SUCCESS
										print "Something went wrong"
										print result3.message
									else:
										print ('lsp bw is null hence modified remote' 
												'JET Router MPLS Bandwidth to 200 mbps  \n')
							else:
								print 'Does not match to IPASO connected interface \n'
						else:
							print 'Unable to collect IPASO connected interface \n'
					# Revert changes in remote JET router if BW is lessthan 200Mbps 
					else:
						print 'IPASO bandwidth is lessthan 200Mbps \n'
						# verify remote JET router MPLS lsp bandwidth configurations
						xml_query = "<get-mpls-lsp-information><extensive/><regex>lsp1</regex></get-mpls-lsp-information>"
						op_command = mgd_service_pb2.ExecuteOpCommandRequest(request_id=5,
																			xml_command=xml_query,
																			out_format=mgd_service_pb2.OPERATION_FORMAT_XML)
						command_result = mgmt_stub2.ExecuteOpCommand(op_command)
						result4 = _get_data(command_result, 5)
						
						rbw1 = re.search (r"<bandwidth>(\d+Mbps)<", result4)
						if rbw1:
							print ('Remote jet router current mpls lsp bandwidth is:',
										rbw1.group(1))
							rlspbw = rbw1.group(1)
							if rlspbw == '200Mbps':
								print ('LSP bw is 200 Mbps hence bandwidth parameters'
												'to be modified in remote JET router \n')
								# Delete MPLS LSP bandwidth
								config_commit = mgd_service_pb2.ConfigCommit(commit_type=mgd_service_pb2.CONFIG_COMMIT,
																					comment="setting mpls bandwidth")
								config = ExecuteCfgCommandRequest(request_id=6,
																	xml_config=lsp_bw_delete,
																	load_type=mgd_service_pb2.CONFIG_LOAD_REPLACE,
																	commit=config_commit)
								result3 = mgmt_stub2.ExecuteCfgCommand(config)
								if result3.status == mgd_service_pb2.SUCCESS:
									print ('Deleted remote JET router MPLS lsp bandwidth'
													'and listening to IPASO bw change notification\n')
								else:
									print result3.message
							else:
								print 'listening to IPASO bw change notification \n'
						else:
							print 'No changes required in remote jet lsp  \n'
			else:
				print 'No action required as received trap is generic'
		else:
		    print 'No action required as received trap is generic'
	return wholeMsg