コード例 #1
0
ファイル: TrippLite.py プロジェクト: cdfredrick/AstroComb_HPF
 def outlet_state(self, set_state=None):
     '''The current state of the outlet. Setting this value to turnOff(1)
     will turn off the outlet. Setting this value to turnOn(2) will turn on
     the outlet. Setting this value to cycle(3) will turn the outlet off, 
     then turn it back on:
         0 = idle or unknown
         1 = off
         2 = on
         3 = cycle (turn off, then turn on
     '''
     if set_state is None:
         # Get current outlet state
         obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletState',
                                         self.device_id, self.outlet_id)
         g = getCmd(SnmpEngine(), self.community, self.transport_target,
                    ContextData(), rfc1902.ObjectType(obj_id))
         errorIndication, errorStatus, errorIndex, varBinds = next(g)
         oid, value = varBinds[0]
         return int(value)
     else:
         # Send outlet state
         obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletCommand',
                                         self.device_id, self.outlet_id)
         g = setCmd(SnmpEngine(), self.community, self.transport_target,
                    ContextData(),
                    rfc1902.ObjectType(obj_id, int(set_state)))
         errorIndication, errorStatus, errorIndex, varBinds = next(g)
コード例 #2
0
def checkSNMP(community, host, port, oid):
    mibBuilder = builder.MibBuilder()
    mibViewController = view.MibViewController(mibBuilder)
    compiler.addMibCompiler(mibBuilder,
                            sources=['http://mibs.snmplabs.com/asn1/@mib@'])
    mibBuilder.loadModules('RFC1213-MIB', 'IF-MIB')
    objectIdentity = rfc1902.ObjectIdentity(oid).resolveWithMib(
        mibViewController)

    errorIndication, errorStatus, errorIndex, varBinds = next(
        getCmd(SnmpEngine(), CommunityData(community),
               UdpTransportTarget((host, port), timeout=1.5, retries=0),
               ContextData(), ObjectType(objectIdentity)))

    if errorIndication:
        print(errorIndication, " : ", host)
    elif errorStatus:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        for varBind in varBinds:
            varB = (' = '.join([x.prettyPrint() for x in varBind]))
            resultado = " ".join(varB.split()[2:])
            return resultado
    return -1
コード例 #3
0
def consultaSNMP(comunidad,host,oid):
		mibBuilder = builder.MibBuilder()
		mibViewController = view.MibViewController(mibBuilder)
		compiler.addMibCompiler(mibBuilder, sources=['file:///usr/local/lib/python2.7/dist-packages/pysnmp/smi/mibs',
																						 'http://mibs.snmplabs.com/asn1/@mib@'])
		mibBuilder.loadModules('RFC1213-MIB','IF-MIB')
		objectIdentity = rfc1902.ObjectIdentity(oid).resolveWithMib(mibViewController)

		errorIndication, errorStatus, errorIndex, varBinds = next(
				getCmd(SnmpEngine(),
							 CommunityData(comunidad),
							 UdpTransportTarget((host, 161)),
							 ContextData(),
							 #ObjectType(ObjectIdentity(oid))))
							 ObjectType( objectIdentity )))

		if errorIndication:
				print(errorIndication)
		elif errorStatus:
				print('%s at %s' % (errorStatus.prettyPrint(),errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
		else:

				for varBind in varBinds:
						varB=(' = '.join([x.prettyPrint() for x in varBind]))
						resultado= " ".join(varB.split()[2:])
		return resultado
コード例 #4
0
def translate_mib(custom_mib_paths, load_mib_modules, name, val):
    """
    Translate OID to MIB
    custom_mib_paths: comma separated mib paths as a string
    load_mib_modules: MIB Module to load e.g. "MIB-FILE-1,MIB-FILE-2"
    Return: Translated OID string and value
    """
    if custom_mib_paths and load_mib_modules:
        try:
            mibBuilder = builder.MibBuilder()
            compiler.addMibCompiler(mibBuilder, sources=custom_mib_paths)
            mibViewController = view.MibViewController(mibBuilder)
            temp_load_mib_modules = load_mib_modules.split(',')
            mibBuilder.loadModules(*temp_load_mib_modules)
        except error.MibNotFoundError as excep:
            testcase_Utils.pNote(" {} Mib Not Found!".format(excep), "Error")
    temp_type = val.__class__.__name__
    if custom_mib_paths and load_mib_modules:
        output = rfc1902.ObjectType(rfc1902.ObjectIdentity(name),
                                    val).resolveWithMib(mibViewController).prettyPrint()
        op_list = output.split(" = ")
        name = op_list[0].strip()
        t_val = op_list[1].strip()
        if temp_type == "Integer":
            testcase_Utils.pNote('%s = %s(%s): %s' %
                                 (name, temp_type, val.prettyPrint(), t_val))
        else:
            if t_val == '': #For empty String
                testcase_Utils.pNote('%s = %s: ""' % (name, temp_type))
            else:
                testcase_Utils.pNote('%s = %s: %s' % (name, temp_type, t_val))
        return name, t_val
    else:
        testcase_Utils.pNote('%s = %s: %s' % (name.prettyPrint(), temp_type, val.prettyPrint()))
        return name.prettyPrint(), val.prettyPrint()
コード例 #5
0
ファイル: trap_inform.py プロジェクト: lightclove/SNMP_usage
def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds,
          cbCtx):
    global pdu_count

    global mibViewController

    print "####################### NEW Notification(PDU_COUNT: {}) #######################".format(
        pdu_count)

    execContext = snmpEngine.observer.getExecutionContext(
        'rfc3412.receiveMessage:request')

    print(
        '#Notification from %s \n#ContextEngineId: "%s" \n#ContextName: "%s" \n#SNMPVER "%s" \n#SecurityName "%s"'
        % ('@'.join([str(x) for x in execContext['transportAddress']]),
           contextEngineId.prettyPrint(), contextName.prettyPrint(),
           execContext['securityModel'], execContext['securityName']))

    for oid, val in varBinds:
        output = rfc1902.ObjectType(
            rfc1902.ObjectIdentity(oid),
            val).resolveWithMib(mibViewController).prettyPrint()

        print output

    pdu_count += 1
コード例 #6
0
def _sendNotification(self,
                      snmpEngine,
                      notificationTarget,
                      notificationName,
                      additionalVarBinds=(),
                      cbFun=None,
                      cbCtx=None,
                      contextName=null,
                      instanceIndex=None):
    if self.snmpContext is None:
        raise error.ProtocolError('SNMP context not specified')
        
    #
    # Here we first expand trap OID into associated OBJECTS
    # and then look them up at context-specific MIB
    #

    mibViewController = snmpEngine.getUserContext('mibViewController')
    if not mibViewController:
        mibViewController = view.MibViewController(snmpEngine.getMibBuilder())
        snmpEngine.setUserContext(mibViewController=mibViewController)

    # Support the following syntax:
    #   '1.2.3.4'
    #   (1,2,3,4)
    #   ('MIB', 'symbol')
    if isinstance(notificationName, (tuple, list)) and \
            notificationName and isinstance(notificationName[0], str):
        notificationName = rfc1902.ObjectIdentity(*notificationName)
    else:
        notificationName = rfc1902.ObjectIdentity(notificationName)

    varBinds = rfc1902.NotificationType(
        notificationName, instanceIndex=instanceIndex
    ).resolveWithMib(mibViewController)

    mibInstrumController = self.snmpContext.getMibInstrum(contextName)

    varBinds = varBinds[:1] + mibInstrumController.readVars(varBinds[1:])

    return self.sendVarBinds(snmpEngine,
                             notificationTarget,
                             self.snmpContext.contextEngineId,
                             contextName,
                             varBinds + list(additionalVarBinds),
                             _sendNotificationCbFun,
                             (cbFun, cbCtx))
コード例 #7
0
ファイル: trap.py プロジェクト: mason-splunk/piat
 def _parse(self):
     """ translate the trap msg with the mib viewer """
     for name, val in self._var_binds:
         var_bind = rfc1902.ObjectType(rfc1902.ObjectIdentity(name), val)
         var_bind.resolveWithMib(self._viewer)
         obj_name = var_bind[0].getMibSymbol()[1]
         value = var_bind[1].prettyPrint()
         self._parsed_data[obj_name] = value
コード例 #8
0
ファイル: TrippLite.py プロジェクト: cdfredrick/AstroComb_HPF
 def query(self, oid, base=False):
     # Get current outlet state
     if base:
         obj_id = rfc1902.ObjectIdentity(self.mib, oid)
     else:
         obj_id = rfc1902.ObjectIdentity(oid)
     g = getCmd(SnmpEngine(), self.community, self.transport_target,
                ContextData(), rfc1902.ObjectType(obj_id))
     errorIndication, errorStatus, errorIndex, varBinds = next(g)
     print(errorIndication, '\n')
     print(errorStatus, '\n')
     print(errorIndex, '\n')
     print(varBinds, '\n')
     oid, value = varBinds[0]
     print(varBinds[0].prettyPrint(), '\n')
     print(oid, '\n')
     print(value, '\n')
コード例 #9
0
ファイル: trap_receiver.py プロジェクト: sfzeng/delfin
    def _cb_fun(self, state_reference, context_engine_id, context_name,
                var_binds, cb_ctx):
        """Callback function to process the incoming trap."""
        exec_context = self.snmp_engine.observer.getExecutionContext(
            'rfc3412.receiveMessage:request')
        LOG.info('#Notification from %s \n#ContextEngineId: "%s" '
                 '\n#ContextName: ''"%s" \n#SNMPVER "%s" \n#SecurityName "%s" '
                 % (
                     '@'.join(
                         [str(x) for x in exec_context['transportAddress']]),
                     context_engine_id.prettyPrint(),
                     context_name.prettyPrint(), exec_context['securityModel'],
                     exec_context['securityName']))

        try:
            # transportAddress contains both ip and port, extract ip address
            source_ip = exec_context['transportAddress'][0]
            alert_source = self._get_alert_source_by_host(source_ip)

            # In case of non v3 version, community string is used to map the
            # trap. Pysnmp library helps to filter traps whose community string
            # are not configured. But if a given community name x is configured
            # for storage1, if the trap is received with x from storage 2,
            # library will allow the trap. So for non v3 version, we need to
            # verify that community name is configured at alert source db for
            # the storage which is sending traps.
            # context_name contains the incoming community string value
            if exec_context['securityModel'] != constants.SNMP_V3_INT \
                    and alert_source['community_string'] != str(context_name):
                msg = (_("Community string not matching with alert source %s, "
                         "dropping it.") % source_ip)
                raise exception.InvalidResults(msg)

            var_binds = [rfc1902.ObjectType(
                rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(
                self.mib_view_controller) for x in var_binds]

            alert = {}

            for var_bind in var_binds:
                oid, value = self._extract_oid_value(var_bind)
                alert[oid] = value

            # Fill additional info to alert info
            alert['transport_address'] = source_ip
            alert['storage_id'] = alert_source['storage_id']

            # Handover to alert processor for model translation and export
            alert_processor.AlertProcessor().process_alert_info(alert)
        except (exception.AlertSourceNotFound,
                exception.StorageNotFound,
                exception.InvalidResults) as e:
            # Log and end the trap processing error flow
            LOG.error(e)
        except Exception as e:
            # Unexpected exception occurred
            LOG.error(e)
コード例 #10
0
ファイル: TrippLite.py プロジェクト: cdfredrick/AstroComb_HPF
 def outlet_ramp_delay(self, set_delay=None):
     '''The number of seconds to delay before powering on the given outlet:
         integer values only
     '''
     if set_delay is None:
         # Get current outlet state
         obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletRampDelay',
                                         self.device_id, self.outlet_id)
         g = getCmd(SnmpEngine(), self.community, self.transport_target,
                    ContextData(), rfc1902.ObjectType(obj_id))
         errorIndication, errorStatus, errorIndex, varBinds = next(g)
         oid, value = varBinds[0]
         return int(value)
     else:
         # Send outlet state
         obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletRampDelay',
                                         self.device_id, self.outlet_id)
         g = setCmd(SnmpEngine(), self.community, self.transport_target,
                    ContextData(), rfc1902.ObjectType(obj_id),
                    int(set_delay))
         errorIndication, errorStatus, errorIndex, varBinds = next(g)
コード例 #11
0
def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
          varBinds, cbCtx):
	logTime=datetime.now().strftime("%m/%d/%Y-%H:%M:%S.%f")[:-3]
	writeLogs('\n\n{}\nNotification from ContextEngineId "{}", ContextName "{}"'.format(logTime,contextEngineId.prettyPrint(), contextName.prettyPrint()))
	print('\nNotification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(),
																		contextName.prettyPrint()))

	varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds]
	for varBind in varBinds:
		writeLogs('\n' + varBind.prettyPrint())
		print(varBind.prettyPrint())
	
	writeLogs('\n')
コード例 #12
0
ファイル: TrippLite.py プロジェクト: cdfredrick/AstroComb_HPF
 def outlet_ramp_action(self, set_action=None):
     '''The ramp action to take on a given outlet when powering on the 
     device:
         0 = remain off
         1 = turn on after delay
     '''
     if set_action is None:
         # Get current outlet state
         obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletRampAction',
                                         self.device_id, self.outlet_id)
         g = getCmd(SnmpEngine(), self.community, self.transport_target,
                    ContextData(), rfc1902.ObjectType(obj_id))
         errorIndication, errorStatus, errorIndex, varBinds = next(g)
         oid, value = varBinds[0]
         return int(value)
     else:
         # Send outlet state
         obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletRampAction',
                                         self.device_id, self.outlet_id)
         g = setCmd(SnmpEngine(), self.community, self.transport_target,
                    ContextData(),
                    rfc1902.ObjectType(obj_id, int(set_action)))
         errorIndication, errorStatus, errorIndex, varBinds = next(g)
コード例 #13
0
ファイル: TrippLite.py プロジェクト: cdfredrick/AstroComb_HPF
 def __init__(self, ip_address, outlet_id, timeout=1, retries=5):
     self.mib = 'TRIPPLITE-PRODUCTS'
     self.transport_addr = (str(ip_address), 161)
     self.transport_target = UdpTransportTarget(self.transport_addr,
                                                timeout=timeout,
                                                retries=retries)
     self.outlet_id = int(outlet_id)
     self.device_id = 1
     self.community = CommunityData('tripplite')
     # Initialize the MIB
     mibBuilder = builder.MibBuilder()
     mibView = view.MibViewController(mibBuilder)
     obj_id = rfc1902.ObjectIdentity(self.mib)
     obj_id.addAsn1MibSource('file://@mib@')
     obj_id.addAsn1MibSource('http://mibs.snmplabs.com/asn1/@mib@')
     obj_id.resolveWithMib(mibView)
コード例 #14
0
ファイル: traplistener.py プロジェクト: FlyearthR/lingi2142-1
    def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
            varBinds, cbCtx):
        # Translate numerical OIDs into human readable form
        varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds]

        # Turn on write permission for everyone
        os.umask(0)
        # Open file, append new data at the end
        with open(os.open(TRAP_LOG_PATH, os.O_CREAT | os.O_WRONLY, 0o777), 'a+') as f:
            t = time.gmtime()
            f.write('TRAP received on %s from ContextEngineId "%s", ContextName "%s" \n' % (time.strftime('%c', t), contextEngineId.prettyPrint(),
                                                                            contextName.prettyPrint()))
            # Write data in file
            for varbind in varBinds:
                f.write(varbind.prettyPrint()+'\n')
            f.write('\n')
コード例 #15
0
 def trap_decoder(cls, snmpEngine, stateReference, contextEngineId,
                  contextName, varBinds, cbCtx):
     """
     Decode the trap messages and saves it in to data repository
     This is call back method which will be coalled internaly for each trap message
     :param transportDispatcher:
     :param transportDomain:
     :param transportAddress:
     :param wholeMsg:
     :return: the actual ASN1 data dumps
     """
     ticks = time.ctime()
     transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(
         stateReference)[-1][0]
     if not cls.data_repo.get(
             "snmp_trap_messages_{}".format(transportAddress)):
         cls.data_repo.update(
             {"snmp_trap_messages_{}".format(transportAddress): []})
     execContext = snmpEngine.observer.getExecutionContext(
         'rfc3412.receiveMessage:request')
     decoded_msg = []
     decoded_msg.append({"time_stamp": ticks})
     decoded_msg.append({"contextEngineId": contextEngineId.prettyPrint()})
     decoded_msg.append({"SNMPVER": execContext["securityModel"]})
     decoded_msg.append({"securityName": execContext['securityName']})
     for oid, val in varBinds:
         try:
             output = rfc1902.ObjectType(
                 rfc1902.ObjectIdentity(oid),
                 val).resolveWithMib(cls.mibViewController).prettyPrint()
         except error.SmiError as excep:
             testcase_Utils.pNote("{} Decode Error!".format(excep), "Error")
         op_list = output.split(" = ")
         oid = op_list[0].strip()
         value = op_list[1].strip()
         decoded_msg.append((oid, value))
     temp_decoded_msg = cls.data_repo.get(
         "snmp_trap_messages_{}".format(transportAddress))
     temp_decoded_msg.append(decoded_msg)
     cls.data_repo.update({
         "snmp_trap_messages_{}".format(transportAddress):
         temp_decoded_msg
     })
コード例 #16
0
ファイル: snmp.py プロジェクト: justkrys/snmp_adapter
def _listen_callback(
    snmp_engine,
    state_reference,
    context_engine_id,
    context_name,
    var_binds,
    callback_context,
):
    transport_domain, transport_address = snmp_engine.msgAndPduDsp.getTransportInfo(
        state_reference)
    print(f"\nNotification from {transport_address}, "
          f"SNMP Engine {context_engine_id.prettyPrint()}, "
          f"Context {context_name.prettyPrint()}")
    for oid, value in var_binds:
        name = rfc1902.ObjectIdentity(oid.prettyPrint())
        name.resolveWithMib(_view_controller)
        print(
            f"    {name.prettyPrint()} ({oid.prettyPrint()}) = {value.prettyPrint()}"
        )
コード例 #17
0
def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus,
          errorIndex, varBindTable, cbCtx):
    if errorIndication:
        print(errorIndication)
        return
    # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception,
    # so we ignore noSuchName error here
    if errorStatus and errorStatus != 2:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?'))
        return  # stop on error
    for varBindRow in varBindTable:
        for varBind in varBindRow:
            print(
                rfc1902.ObjectType(rfc1902.ObjectIdentity(varBind[0]),
                                   varBind[1]).resolveWithMib(
                                       mibViewController).prettyPrint())
    return 1  # signal dispatcher to continue
コード例 #18
0
ファイル: test_snmp.py プロジェクト: lloydwuhb/ceilometer
    def test_pysnmp_ver43(self):
        # Test pysnmp version >=4.3 compatibility of ObjectIdentifier
        from distutils.version import StrictVersion
        import pysnmp

        has43 = StrictVersion(pysnmp.__version__) >= StrictVersion('4.3.0')
        oid = '1.3.6.4.1.2021.11.57.0'

        if has43:
            from pysnmp.entity import engine
            from pysnmp.smi import rfc1902
            from pysnmp.smi import view
            snmp_engine = engine.SnmpEngine()
            mvc = view.MibViewController(snmp_engine.getMibBuilder())
            name = rfc1902.ObjectIdentity(oid)
            name.resolveWithMib(mvc)
        else:
            from pysnmp.proto import rfc1902
            name = rfc1902.ObjectName(oid)

        self.assertEqual(oid, str(name))
コード例 #19
0
def cbReceiverSnmp(snmpEngine, stateReference, contextEngineId, contextName,
                   varBinds, cbCtx):
    transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(
        stateReference)
    if (bDebug):
        szDebug = str(
            "Notification From: %s, Domain: %s, SNMP Engine: %s, Context: %s" %
            (transportAddress, transportDomain, contextEngineId.prettyPrint(),
             contextName.prettyPrint()))
        print(szDebug)
        logFile.write(szDebug)
        logFile.flush()

    # Create output String
    szOut = "Trap Source{}, Trap OID {}".format(transportAddress,
                                                transportDomain)

    varBinds = [
        rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]),
                           x[1]).resolveWithMib(mibViewController)
        for x in varBinds
    ]

    for name, val in varBinds:
        # Append to output String
        szOut = szOut + ", Oid: {}, Value: {}".format(name.prettyPrint(),
                                                      val.prettyPrint())

        if isinstance(val, OctetString):
            if (name.prettyPrint() != "SNMP-COMMUNITY-MIB::snmpTrapAddress.0"):
                szOctets = val.asOctets()  #.rstrip('\r').rstrip('\n')
                szOut = szOut + ", Octets: {}".format(szOctets)
        if (bDebug):
            print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
    outputFile.write(szOut)
    if "\n" not in szOut:
        outputFile.write("\n")
    outputFile.flush()
コード例 #20
0
    def _cb_fun(self, state_reference, context_engine_id, context_name,
                var_binds, cb_ctx):
        """Callback function to process the incoming trap."""
        exec_context = self.snmp_engine.observer.getExecutionContext(
            'rfc3412.receiveMessage:request')
        LOG.info('#Notification from %s \n#ContextEngineId: "%s" '
                 '\n#ContextName: '
                 '"%s" \n#SNMPVER "%s" \n#SecurityName "%s" ' %
                 ('@'.join([str(x) for x in exec_context['transportAddress']]),
                  context_engine_id.prettyPrint(), context_name.prettyPrint(),
                  exec_context['securityModel'], exec_context['securityName']))

        var_binds = [
            rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]),
                               x[1]).resolveWithMib(self.mib_view_controller)
            for x in var_binds
        ]
        alert = {}

        for var_bind in var_binds:
            oid, value = self._extract_oid_value(var_bind)
            alert[oid] = value

        # Fill additional info to alert_info
        # transportAddress contains both ip and port, extract ip address
        alert['transport_address'] = exec_context['transportAddress'][0]

        # Handover trap info to alert processor for model translation and export
        try:
            alert_processor.AlertProcessor().process_alert_info(alert)
        except (exception.AccessInfoNotFound, exception.StorageNotFound,
                exception.InvalidResults) as e:
            # Log and end the trap processing error flow
            LOG.error(e)
        except Exception as e:
            # Unexpected exception occurred
            LOG.error(e)
コード例 #21
0
    def _configureMibObjects(self, configDict):

        mibBuilder = builder.MibBuilder()
        mibViewController = view.MibViewController(mibBuilder)

        compiler.addMibCompiler(
            mibBuilder, sources=configDict['snmp'].get('mibs', ()))

        self._sysUpTime = rfc1902.ObjectIdentity(
            'SNMPv2-MIB', 'sysUpTime', 0).resolveWithMib(mibViewController)

        self._snmpTrapOID = rfc1902.ObjectIdentity(
            'SNMPv2-MIB', 'snmpTrapOID', 0).resolveWithMib(mibViewController)

        self._rtbrickSyslogTrap = rfc1902.ObjectIdentity(
            'RTBRICK-SYSLOG-MIB', 'rtbrickSyslogTrap', 1).resolveWithMib(mibViewController)

        self._syslogMsgNumber = rfc1902.ObjectIdentity(
            'RTBRICK-SYSLOG-MIB', 'syslogMsgNumber', 0).resolveWithMib(mibViewController)

        self._syslogMsgFacility = rfc1902.ObjectIdentity(
            'RTBRICK-SYSLOG-MIB', 'syslogMsgFacility', 0).resolveWithMib(mibViewController)

        self._syslogMsgSeverity = rfc1902.ObjectIdentity(
            'RTBRICK-SYSLOG-MIB', 'syslogMsgSeverity', 0).resolveWithMib(mibViewController)

        self._syslogMsgText = rfc1902.ObjectIdentity(
            'RTBRICK-SYSLOG-MIB', 'syslogMsgText', 0).resolveWithMib(mibViewController)

        self.moduleLogger.info(
            f'Notifications will include these SNMP objects: '
            f'{self._sysUpTime}=TimeTicks, '
            f'{self._snmpTrapOID}={self._rtbrickSyslogTrap} '
            f'{self._syslogMsgNumber}=Unsigned32 '
            f'{self._syslogMsgFacility}=OctetString '
            f'{self._syslogMsgSeverity}=Integer32 '
            f'{self._syslogMsgText}=OctetString')
コード例 #22
0
or the other way around.

The code below does not explicitly add MIB compiler - that happens
behind the scenes. Examples below try to demo different kinds
of MIB objects to work with.
"""#
from pysnmp.smi import builder, view, rfc1902, error

# MIB Builder manages pysnmp MIBs
mibBuilder = builder.MibBuilder()

# MIB View Controller implements various queries to loaded MIBs
mibView = view.MibViewController(mibBuilder)

# Obtain MIB object information by MIB object name
mibVar = rfc1902.ObjectIdentity('IF-MIB', 'ifInOctets', 1)

# Optionally attach PySMI MIB compiler to MIB Builder that would
# create pysnmp MIBs on demand from ASN.1 sources downloaded from
# a web site.
try:
    mibVar.addAsn1MibSource('http://mibs.snmplabs.com/asn1/@mib@')
except error.SmiError:
    print('WARNING: not using MIB compiler (PySMI not installed)')

mibVar.resolveWithMib(mibView)

print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar))

# Obtain MIB object information by its [sequence] OID
mibVar = rfc1902.ObjectIdentity(tuple(mibVar)).resolveWithMib(mibView)
コード例 #23
0
ファイル: mib.py プロジェクト: cjj2003/APC-SNMP
mibSrcs = mb.getMibSources() + (builder.DirMibSource(
    os.path.join(os.getcwd(), "CompiledMIBs")), )
mb.setMibSources(*mibSrcs)
print(mibSrcs)
mb.loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB', 'PowerNet-MIB', 'UPS-MIB')
vc = view.MibViewController(mb)

varBinds = [
    ('1.3.6.1.2.1.1.3.0', 9041620),
    ('1.3.6.1.6.3.1.1.4.1.0', '1.3.6.1.4.1.318.0.636'),
    ('1.3.6.1.4.1.318.2.3.3.0',
     b'UPS: On battery power in response to distorted input.'),
    ('1.3.6.1.2.1.33.1.2.3.0', 20),
    ('1.3.6.1.2.1.33.1.2.2.0', 0),
    ('1.3.6.1.2.1.33.1.9.7.0', 2),
]

for k, v in varBinds:
    q = tuple(int(kk) for kk in k.split('.'))
    print(k, q)
    try:
        print(vc.getNodeName(q))
    except:
        print("Fail 1!")
    try:
        vb = rfc1902.ObjectType(rfc1902.ObjectIdentity(k),
                                v).resolveWithMib(vc)
        print(vb.prettyPrint())
    except:
        print("Fail 2!")
コード例 #24
0
def _parse_mib_object(arg, last=False):
    if '::' in arg:
        return rfc1902.ObjectIdentity(*arg.split('::', 1), last=last)

    else:
        return univ.ObjectIdentifier(arg)
# Assemble MIB browser
mibBuilder = builder.MibBuilder()
mibViewController = view.MibViewController(mibBuilder)
compiler.addMibCompiler(mibBuilder,
                        sources=[
                            'file:///usr/share/snmp/mibs',
                            'http://mibs.snmplabs.com/asn1/@mib@'
                        ])

# Pre-load MIB modules we expect to work with
mibBuilder.loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB')

# This is what we can get in TRAP PDU
varBinds = [('1.3.6.1.2.1.1.3.0', 12345),
            ('1.3.6.1.6.3.1.1.4.1.0', '1.3.6.1.6.3.1.1.5.2'),
            ('1.3.6.1.6.3.18.1.3.0', '0.0.0.0'), ('1.3.6.1.6.3.18.1.4.0', ''),
            ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'),
            ('1.3.6.1.2.1.1.1.0', 'my system')]

# Run var-binds through MIB resolver
# You may want to catch and ignore resolution errors here
varBinds = [
    rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]),
                       x[1]).resolveWithMib(mibViewController)
    for x in varBinds
]

for varBind in varBinds:
    print(varBind.prettyPrint())
コード例 #26
0
 elif opt[0] == '--logging-method':
     loggingMethod = opt[1].split(':')
 elif opt[0] == '--log-level':
     loggingLevel = opt[1]
 if opt[0] == '--quiet':
     verboseFlag = False
 # obsolete begin
 elif opt[0] == '--start-oid':
     startOID = univ.ObjectIdentifier(opt[1])
 elif opt[0] == '--stop-oid':
     stopOID = univ.ObjectIdentifier(opt[1])
 # obsolete end
 if opt[0] == '--mib-source':
     mibSources.append(opt[1])
 if opt[0] == '--start-object':
     startOID = rfc1902.ObjectIdentity(*opt[1].split('::', 1))
 if opt[0] == '--stop-object':
     stopOID = rfc1902.ObjectIdentity(*opt[1].split('::', 1),
                                      **dict(last=True))
 elif opt[0] == '--output-dir':
     outputDir = opt[1]
 elif opt[0] == '--transport-id-offset':
     try:
         transportIdOffset = max(0, int(opt[1]))
     except:
         sys.stderr.write('ERROR: %s\r\n%s\r\n' %
                          (sys.exc_info()[1], helpMessage))
         sys.exit(-1)
 elif opt[0] == '--listen-interface':
     listenInterface = opt[1]
 elif opt[0] == '--promiscuous-mode':
コード例 #27
0
ファイル: oid_db.py プロジェクト: rtbrick/bdsSnmpAdaptor
    def add(self, mibName, mibSymbol, *indices, value=None,
            valueFormat=None, code=None):
        """Add SNMP MIB managed object instance to the OID DB

        Args:
            mibName (str): MIB name e.g. SNMPv2-MIB. This MIB must be in MIB
                search path.
            mibSymbol (str): MIB symbol name
            indices (vararg): one or more objects representing indices.
                Should be `0` for scalars.
            value: put this value into MIB managed object. This is what SNMP
                manager will get in response. The `None` sentinel refreshes
                existing object.
            valueFormat (string): 'hexValue' to indicate hex `value` initializer.
                Optional.
            code (string): compile and use this Python code snippet for getting a
                value at run time. Optional.

        Examples:

          add('SNMPv2-MIB', 'sysDescr', 0, value='hello world')
          add('SNMPv2-MIB', 'sysDescr', 0, value='10101010', valueFormat='binValue')
          add('SNMPv2-MIB', 'sysDescr', 0, code='print("hello world")')

        """
        if value is None:
            objectIdentity = rfc1902.ObjectIdentity(
                mibName, mibSymbol, *indices).resolveWithMib(self._mibViewController)

            try:
                oidDbItem = self._oids[objectIdentity.getOid()]

            except KeyError:
                raise error.BdsError(
                    'Initial value for managed %s::%s object must be '
                    'provided' % (mibName, mibSymbol))

        else:
            obj = rfc1902.ObjectType(
                rfc1902.ObjectIdentity(mibName, mibSymbol, *indices), value)

            objectIdentity, objectSyntax = obj.resolveWithMib(self._mibViewController)

            try:
                representation = {valueFormat if valueFormat else 'value': value}
                objectSyntax = objectSyntax.clone(**representation)

                if code:
                    code = compile(code, '<%s::%s>' % (mibName, mibSymbol), 'exec')

                oidDbItem = OidDbItem(
                    oid=objectIdentity.getOid(),
                    name=objectIdentity.getMibSymbol()[1],
                    value=objectSyntax,
                    code=code
                )

            except Exception as exc:
                raise error.BdsError(
                    'Error setting managed object %s (%s) of type %s to value '
                    '"%s"' % ('::'.join(objectIdentity.getMibSymbol()),
                              objectIdentity.getOid(), objectSyntax, value))

        self.moduleLogger.debug(
            f'{"updating" if oidDbItem.oid in self._oids else "adding"} '
            f'{oidDbItem.oid} {"<code>" if code else oidDbItem.value.prettyPrint()}')

        # put new OID online immediately
        self._oids[oidDbItem.oid] = oidDbItem

        self._dirty = True

        now = time.time()

        mibObject = mibName, mibSymbol

        # We update two DBs for some time while use only one, eventually
        # we drop the older DB and use the newer one. This effectively
        # expires DB entries that do not get updated for some time.
        self._mibObjects[mibObject][oidDbItem.oid] = oidDbItem
        self._candidateMibObjects[mibObject][oidDbItem.oid] = oidDbItem

        if self._expireBy < now:

            # put candidate objects online
            (self._mibObjects[mibObject],
             self._candidateMibObjects[mibObject]) = (
                self._candidateMibObjects[mibObject],
                self._mibObjects[mibObject])

            # prepare new candidate objects dict - drop everything it has,
            # most importantly, entries that have not been updated
            # N.B. this only works for tablular SNMP objects
            self._candidateMibObjects[mibObject].clear()

            # stale entries expire in two runs of `.add`
            self._expireBy = now + self.EXPIRE_PERIOD / 2

            # drop all online OIDs
            self._oids.clear()

            # put recently updated OIDs online
            for oidItems in self._mibObjects.values():
                self._oids.update(oidItems)
コード例 #28
0
    if errorStatus and errorStatus != 2:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?'))
        return  # stop on error
    for varBindRow in varBindTable:
        for varBind in varBindRow:
            print(
                rfc1902.ObjectType(rfc1902.ObjectIdentity(varBind[0]),
                                   varBind[1]).resolveWithMib(
                                       mibViewController).prettyPrint())
    return 1  # signal dispatcher to continue


# Prepare initial request to be sent
cmdgen.NextCommandGenerator().sendVarBinds(
    snmpEngine,
    'my-router',
    None,
    '',  # contextEngineId, contextName
    [
        rfc1902.ObjectType(rfc1902.ObjectIdentity(
            'iso.org.dod')).resolveWithMib(mibViewController),
        rfc1902.ObjectType(rfc1902.ObjectIdentity(
            'IF-MIB', 'ifMIB')).resolveWithMib(mibViewController)
    ],
    cbFun)

# Run I/O dispatcher which would send pending queries and process responses
snmpEngine.transportDispatcher.runDispatcher()
コード例 #29
0
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(snmpEngine, 'my-notification', 'my-filter',
                             'all-my-managers', 'trap')

# Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
# and SecurityName
config.addContext(snmpEngine, '')
config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))

# *** SNMP engine configuration is complete by this line ***

# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()

# Build and submit notification message to dispatcher
ntfOrg.sendVarBinds(
    snmpEngine,
    'my-notification',  # notification targets
    None,
    '',  # contextEngineId, contextName
    rfc1902.NotificationType(
        rfc1902.ObjectIdentity('IF-MIB', 'linkUp'),
        instanceIndex=instanceIndex,
        objects=objects).resolveWithMib(mibViewController))

print('Notification is scheduled to be sent')

# Run I/O dispatcher which would send pending message and process response
snmpEngine.transportDispatcher.runDispatcher()