Beispiel #1
0
 def prettyPrint(self):
     if self.__state & self.stClean:
         return ' '.join([
             '%s = %s' % (x[0].prettyPrint(), x[1].prettyPrint())
             for x in self.__varBinds
         ])
     else:
         raise SmiError('%s object not fully initialized' %
                        self.__class__.__name__)
Beispiel #2
0
 def __init__(self, objectIdentity, instanceIndex=(), objects={}):
     if not isinstance(objectIdentity, ObjectIdentity):
         raise SmiError('initializer should be ObjectIdentity instance, not %r' % (objectIdentity,))
     self.__objectIdentity = objectIdentity
     self.__instanceIndex = instanceIndex
     self.__objects = objects
     self.__varBinds = []
     self.__additionalVarBinds = []
     self.__state = self.stDirty
Beispiel #3
0
 def __getattr__(self, attr):
     if self.__state & self.stClean:
         if attr in ('asTuple', 'clone', 'subtype', 'isPrefixOf',
                     'isSameTypeWith', 'isSuperTypeOf', 'getTagSet',
                     'getEffectiveTagSet', 'getTagMap', 'tagSet', 'index'):
             return getattr(self.__oid, attr)
         raise AttributeError(attr)
     else:
         raise SmiError('%s object not properly initialized for accessing %s' % (self.__class__.__name__, attr))
Beispiel #4
0
def getTargetParams(snmpEngine, paramsName):
    mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

    snmpTargetParamsEntry, = mibBuilder.importSymbols(
        'SNMP-TARGET-MIB', 'snmpTargetParamsEntry'
    )

    cache = snmpEngine.getUserContext('getTargetParams')
    if cache is None:
        cache = {'id': -1}
        snmpEngine.setUserContext(getTargetParams=cache)

    if cache['id'] != snmpTargetParamsEntry.branchVersionId:
        cache['nameToParamsMap'] = {}

    nameToParamsMap = cache['nameToParamsMap']

    if paramsName not in nameToParamsMap:
        (snmpTargetParamsMPModel, snmpTargetParamsSecurityModel,
         snmpTargetParamsSecurityName,
         snmpTargetParamsSecurityLevel) = mibBuilder.importSymbols(
            'SNMP-TARGET-MIB', 'snmpTargetParamsMPModel',
            'snmpTargetParamsSecurityModel', 'snmpTargetParamsSecurityName',
            'snmpTargetParamsSecurityLevel'
        )

        tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(paramsName)

        try:
            snmpTargetParamsMPModel = snmpTargetParamsMPModel.getNode(
                snmpTargetParamsMPModel.name + tblIdx
            ).syntax

            snmpTargetParamsSecurityModel = snmpTargetParamsSecurityModel.getNode(
                snmpTargetParamsSecurityModel.name + tblIdx
            ).syntax

            snmpTargetParamsSecurityName = snmpTargetParamsSecurityName.getNode(
                snmpTargetParamsSecurityName.name + tblIdx
            ).syntax

            snmpTargetParamsSecurityLevel = snmpTargetParamsSecurityLevel.getNode(
                snmpTargetParamsSecurityLevel.name + tblIdx
            ).syntax

        except NoSuchInstanceError:
            raise SmiError('Parameters %s not configured at LCD' % paramsName)

        nameToParamsMap[paramsName] = (snmpTargetParamsMPModel,
                                       snmpTargetParamsSecurityModel,
                                       snmpTargetParamsSecurityName,
                                       snmpTargetParamsSecurityLevel)

        cache['id'] = snmpTargetParamsEntry.branchVersionId

    return nameToParamsMap[paramsName]
Beispiel #5
0
    def cloneFromName(self, value, impliedFlag, parentRow, parentIndices):
        kind = value[0]
        clone = self.clone()

        if kind == 1:
            clone['internet'] = tuple(value[1:5])
            return clone, value[5:]

        else:
            raise SmiError('unknown NetworkAddress type %r' % (kind, ))
Beispiel #6
0
 def prettyPrint(self):
     if self.__state & self.stClean:
         s = rfc1902.OctetString()
         return '%s::%s%s%s' % (
             self.__modName, self.__symName,
             self.__indices and '.' or '',
             '.'.join([x.isSuperTypeOf(s) and '"%s"' % x.prettyPrint() or x.prettyPrint() for x in self.__indices])
         )
     else:
         raise SmiError('%s object not fully initialized' % self.__class__.__name__)
Beispiel #7
0
def getTargetNames(snmpEngine, tag):
    mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

    snmpTargetAddrEntry, = mibBuilder.importSymbols(
        'SNMP-TARGET-MIB', 'snmpTargetAddrEntry')

    cache = snmpEngine.getUserContext('getTargetNames')
    if cache is None:
        cache = {'id': -1}
        snmpEngine.setUserContext(getTargetNames=cache)

    if cache['id'] == snmpTargetAddrEntry.branchVersionId:
        tagToTargetsMap = cache['tagToTargetsMap']

    else:
        cache['tagToTargetsMap'] = {}

        tagToTargetsMap = cache['tagToTargetsMap']

        (SnmpTagValue, snmpTargetAddrName,
         snmpTargetAddrTagList) = mibBuilder.importSymbols(
            'SNMP-TARGET-MIB', 'SnmpTagValue', 'snmpTargetAddrName',
            'snmpTargetAddrTagList'
        )

        mibNode = snmpTargetAddrTagList

        while True:
            try:
                mibNode = snmpTargetAddrTagList.getNextNode(mibNode.name)

            except NoSuchInstanceError:
                break

            idx = mibNode.name[len(snmpTargetAddrTagList.name):]

            _snmpTargetAddrName = snmpTargetAddrName.getNode(snmpTargetAddrName.name + idx).syntax

            for _tag in mibNode.syntax.asOctets().split():
                _tag = SnmpTagValue(_tag)

                if _tag not in tagToTargetsMap:
                    tagToTargetsMap[_tag] = []

                tagToTargetsMap[_tag].append(_snmpTargetAddrName)

        cache['id'] = snmpTargetAddrEntry.branchVersionId

    if tag not in tagToTargetsMap:
        raise SmiError('Transport tag %s not configured at LCD' % tag)

    return tagToTargetsMap[tag]
Beispiel #8
0
    def prettyPrint(self):
        if self._state & self.ST_CLEAN:
            s = rfc1902.OctetString()

            return '%s::%s%s%s' % (
                self._modName, self._symName, self._indices and '.'
                or '', '.'.join(
                    (x.isSuperTypeOf(s, matchConstraints=False) and '"%s"' %
                     x.prettyPrint() or x.prettyPrint())
                    for x in self._indices))

        else:
            raise SmiError('%s object not fully initialized' %
                           self.__class__.__name__)
Beispiel #9
0
def getNotificationInfo(snmpEngine, notificationTarget):
    mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController
    # Transport endpoint
    snmpNotifyEntry, = mibInstrumController.mibBuilder.importSymbols(
        'SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry'
        )
    tblIdx = snmpNotifyEntry.getInstIdFromIndices(
        notificationTarget
        )
    ((v, snmpNotifyTag),
     (v, snmpNotifyType)) = mibInstrumController.readVars(
        ((snmpNotifyEntry.name + (2,) + tblIdx, None),
         (snmpNotifyEntry.name + (3,) + tblIdx, None))
        )

    if noSuchInstance.isSameTypeWith(snmpNotifyTag):
        raise SmiError('Target %s not configured at SMI' % notificationTarget)

    return snmpNotifyTag, snmpNotifyType
Beispiel #10
0
def getNotificationInfo(snmpEngine, notificationTarget):
    mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

    snmpNotifyEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB',
                                                'snmpNotifyEntry')

    cache = snmpEngine.getUserContext('getNotificationInfo')
    if cache is None:
        cache = {'id': -1}
        snmpEngine.setUserContext(getNotificationInfo=cache)

    if cache['id'] != snmpNotifyEntry.branchVersionId:
        cache['targetToNotifyMap'] = {}

    targetToNotifyMap = cache['targetToNotifyMap']

    if notificationTarget not in targetToNotifyMap:
        (snmpNotifyTag,
         snmpNotifyType) = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB',
                                                    'snmpNotifyTag',
                                                    'snmpNotifyType')

        tblIdx = snmpNotifyEntry.getInstIdFromIndices(notificationTarget)

        try:
            snmpNotifyTag = snmpNotifyTag.getNode(
                snmpNotifyTag.name + tblIdx
            ).syntax
            snmpNotifyType = snmpNotifyType.getNode(
                snmpNotifyType.name + tblIdx
            ).syntax

        except NoSuchInstanceError:
            raise SmiError('Target %s not configured at LCD' % notificationTarget)

        targetToNotifyMap[notificationTarget] = (
            snmpNotifyTag,
            snmpNotifyType
        )

        cache['id'] = snmpNotifyEntry.branchVersionId

    return targetToNotifyMap[notificationTarget]
Beispiel #11
0
def getTargetInfo(snmpEngine, snmpTargetAddrName):
    # Transport endpoint
    ( snmpTargetAddrTDomain,
      snmpTargetAddrTAddress,
      snmpTargetAddrTimeout,
      snmpTargetAddrRetryCount,
      snmpTargetAddrParams ) = getTargetAddr(snmpEngine, snmpTargetAddrName)

    mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController

    # Target params
    snmpTargetParamsEntry, = mibInstrumController.mibBuilder.importSymbols(
        'SNMP-TARGET-MIB', 'snmpTargetParamsEntry'
        )

    tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(
        snmpTargetAddrParams
        )
    ((v, snmpTargetParamsMPModel),
     (v, snmpTargetParamsSecurityModel),
     (v, snmpTargetParamsSecurityName),
     (v, snmpTargetParamsSecurityLevel)) = mibInstrumController.readVars(
        ((snmpTargetParamsEntry.name + (2,) + tblIdx, None),
         (snmpTargetParamsEntry.name + (3,) + tblIdx, None),
         (snmpTargetParamsEntry.name + (4,) + tblIdx, None),
         (snmpTargetParamsEntry.name + (5,) + tblIdx, None))
        )
    
    if noSuchInstance.isSameTypeWith(snmpTargetParamsSecurityName):
        raise SmiError('Parameters %s not configured at SMI' % snmpTargetAddrParams)

    return ( snmpTargetAddrTDomain,
             snmpTargetAddrTAddress,
             snmpTargetAddrTimeout,
             snmpTargetAddrRetryCount,
             snmpTargetParamsMPModel,
             snmpTargetParamsSecurityModel,
             snmpTargetParamsSecurityName,
             snmpTargetParamsSecurityLevel )
Beispiel #12
0
    def addVarBinds(self, *varBinds):
        """Appends variable-binding to notification.

        Parameters
        ----------
        *varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
            One or more :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
            instances.

        Returns
        -------
        : :py:class:`~pysnmp.smi.rfc1902.NotificationType`
            reference to itself

        Notes
        -----
        This method can be used to add custom variable-bindings to
        notification message in addition to MIB variables specified
        in NOTIFICATION-TYPE->OBJECTS clause.

        Examples
        --------
        >>> nt = NotificationType(ObjectIdentity('IP-MIB', 'linkDown'))
        >>> nt.addVarBinds(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
        NotificationType(ObjectIdentity('IP-MIB', 'linkDown'), (), {})
        >>>
        """
        debug.logger & debug.FLAG_MIB and debug.logger(
            'additional var-binds: %r' % (varBinds, ))

        if self._state & self.ST_CLEAN:
            raise SmiError('%s object is already sealed' %
                           self.__class__.__name__)

        else:
            self._additionalVarBinds.extend(varBinds)

        return self
Beispiel #13
0
def getTargetAddr(snmpEngine, snmpTargetAddrName):
    mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController
    # Transport endpoint
    snmpTargetAddrEntry, = mibInstrumController.mibBuilder.importSymbols(
        'SNMP-TARGET-MIB', 'snmpTargetAddrEntry'
        )
    tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(
        snmpTargetAddrName
        )

    ((v, snmpTargetAddrTDomain),
     (v, snmpTargetAddrTAddress),
     (v, snmpTargetAddrTimeout),
     (v, snmpTargetAddrRetryCount),
     (v, snmpTargetAddrParams)) = mibInstrumController.readVars(
        ((snmpTargetAddrEntry.name + (2,) + tblIdx, None),
         (snmpTargetAddrEntry.name + (3,) + tblIdx, None),
         (snmpTargetAddrEntry.name + (4,) + tblIdx, None),
         (snmpTargetAddrEntry.name + (5,) + tblIdx, None),
         (snmpTargetAddrEntry.name + (7,) + tblIdx, None))       
        )

    if noSuchInstance.isSameTypeWith(snmpTargetAddrParams):
        raise SmiError('Target %s not configured at SMI' % snmpTargetAddrName)

    if snmpTargetAddrTDomain == config.snmpUDPDomain:
        SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress')
        snmpTargetAddrTAddress = tuple(
            SnmpUDPAddress(snmpTargetAddrTAddress)
            )

    return ( snmpTargetAddrTDomain,
             snmpTargetAddrTAddress,
             snmpTargetAddrTimeout,
             snmpTargetAddrRetryCount,
             snmpTargetAddrParams )
Beispiel #14
0
    def getLabel(self):
        """Returns symbolic path to this MIB variable.

        Meaning a sequence of symbolic identifications for each of parent
        MIB objects in MIB tree.

        Returns
        -------
        tuple
            sequence of names of nodes in a MIB tree from the top of the tree
            towards this MIB variable.

        Raises
        ------
        SmiError
           If MIB variable conversion has not been performed.

        Notes
        -----
        Returned sequence may not contain full path to this MIB variable
        if some symbols are now known at the moment of MIB look up.

        Examples
        --------
        >>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
        >>> objectIdentity.resolveWithMib(mibViewController)
        >>> objectIdentity.getOid()
        ('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr')
        >>>

        """
        if self.__state & self.stClean:
            return self.__label
        else:
            raise SmiError('%s object not fully initialized' %
                           self.__class__.__name__)
Beispiel #15
0
 def prettyPrint(self):
     if self.__state & self.stClean:
         return '%s = %s' % (self.__args[0].prettyPrint(),
                             self.__args[1].prettyPrint())
     else:
         raise SmiError('%s object not fully initialized' % self.__class__.__name__)
Beispiel #16
0
 def __getitem__(self, i):
     if self.__state & self.stClean:
         return self.__varBinds[i]
     else:
         raise SmiError('%s object not fully initialized' % self.__class__.__name__)
Beispiel #17
0
 def __init__(self, objectIdentity, objectSyntax=rfc1905.unSpecified):
     if not isinstance(objectIdentity, ObjectIdentity):
         raise SmiError('initializer should be ObjectIdentity instance, not %r' % (objectIdentity,))
     self.__args = [objectIdentity, objectSyntax]
     self.__state = self.stDirty
Beispiel #18
0
    def resolveWithMib(self, mibViewController):
        """Perform MIB variable ID and associated value conversion.

        Parameters
        ----------
        mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
            class instance representing MIB browsing functionality.

        Returns
        -------
        : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
            reference to itself

        Raises
        ------
        SmiError
           In case of fatal MIB hanling errora

        Notes
        -----
        Calling this method involves
        :py:meth:`~pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib`
        method invocation.

        Examples
        --------
        >>> objectType = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386')
        >>> objectType.resolveWithMib(mibViewController)
        ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), DisplayString('Linux i386'))
        >>> str(objectType)
        'SNMPv2-MIB::sysDescr."0" = Linux i386'
        >>>

        """
        if self.__state & self.stClean:
            return self

        self.__args[0].resolveWithMib(mibViewController)

        MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar',
                                                                               'MibTableColumn')

        if not isinstance(self.__args[0].getMibNode(),
                          (MibScalar, MibTableColumn)):
            if not isinstance(self.__args[1], AbstractSimpleAsn1Item):
                raise SmiError('MIB object %r is not OBJECT-TYPE (MIB not loaded?)' % (self.__args[0],))
            self.__state |= self.stClean
            return self

        if isinstance(self.__args[1], (rfc1905.UnSpecified,
                                       rfc1905.NoSuchObject,
                                       rfc1905.NoSuchInstance,
                                       rfc1905.EndOfMibView)):
            self.__state |= self.stClean
            return self

        try:
            self.__args[1] = self.__args[0].getMibNode().getSyntax().clone(self.__args[1])
        except PyAsn1Error:
            raise SmiError('MIB object %r having type %r failed to cast value %r: %s' % (
                self.__args[0].prettyPrint(), self.__args[0].getMibNode().getSyntax().__class__.__name__, self.__args[1],
                sys.exc_info()[1]))

        if self.__args[1].isSuperTypeOf(rfc1902.ObjectIdentifier()):
            self.__args[1] = ObjectIdentity(self.__args[1]).resolveWithMib(mibViewController)

        self.__state |= self.stClean

        debug.logger & debug.flagMIB and debug.logger('resolved %r syntax is %r' % (self.__args[0], self.__args[1]))

        return self
Beispiel #19
0
 def __radd__(self, other):
     if self.__state & self.stClean:
         return other + self.__oid
     else:
         raise SmiError('%s object not properly initialized' % self.__class__.__name__)
Beispiel #20
0
 def __hash__(self):
     if self.__state & self.stClean:
         return hash(self.__oid)
     else:
         raise SmiError('%s object not properly initialized' % self.__class__.__name__)
Beispiel #21
0
 def __nonzero__(self):
     if self.__state & self.stClean:
         return self.__oid != 0
     else:
         raise SmiError('%s object not properly initialized' % self.__class__.__name__)
Beispiel #22
0
    def resolveWithMib(self, mibViewController, ignoreErrors=True):
        """Perform MIB variable ID and associated value conversion.

        Parameters
        ----------
        mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
            class instance representing MIB browsing functionality.

        Other Parameters
        ----------------
        ignoreErrors: :py:class:`bool`
            If `True` (default), ignore MIB object name or value casting
            failures if possible.

        Returns
        -------
        : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
            reference to itself

        Raises
        ------
        SmiError
           In case of fatal MIB hanling errora

        Notes
        -----
        Calling this method involves
        :py:meth:`~pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib`
        method invocation.

        Examples
        --------
        >>> from pysmi.hlapi import varbinds
        >>> mibViewController = varbinds.AbstractVarBinds.getMibViewController( engine )
        >>> objectType = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386')
        >>> objectType.resolveWithMib(mibViewController)
        ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), DisplayString('Linux i386'))
        >>> str(objectType)
        'SNMPv2-MIB::sysDescr."0" = Linux i386'
        >>>

        """
        if self._state & self.ST_CLEAM:
            return self

        self._args[0].resolveWithMib(mibViewController)

        MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols(
            'SNMPv2-SMI', 'MibScalar', 'MibTableColumn')

        if not isinstance(self._args[0].getMibNode(),
                          (MibScalar, MibTableColumn)):

            if (ignoreErrors
                    and not isinstance(self._args[1], AbstractSimpleAsn1Item)):
                raise SmiError('MIB object %r is not OBJECT-TYPE '
                               '(MIB not loaded?)' % (self._args[0], ))

            self._state |= self.ST_CLEAM

            return self

        if isinstance(self._args[1],
                      (rfc1905.UnSpecified, rfc1905.NoSuchObject,
                       rfc1905.NoSuchInstance, rfc1905.EndOfMibView)):
            self._state |= self.ST_CLEAM
            return self

        syntax = self._args[0].getMibNode().getSyntax()

        try:
            self._args[1] = syntax.clone(self._args[1])

        except PyAsn1Error as exc:
            err = ('MIB object %r having type %r failed to cast value '
                   '%r: %s' %
                   (self.__args[0].prettyPrint(),
                    self.__args[0].getMibNode().getSyntax().__class__.__name__,
                    self.__args[1], sys.exc_info()[1]))

            debug.logger & debug.FLAG_MIB and debug.logger(err)

            if (not ignoreErrors
                    or not isinstance(self.__args[1], AbstractSimpleAsn1Item)):
                raise SmiError(err)

        if rfc1902.ObjectIdentifier().isSuperTypeOf(self._args[1],
                                                    matchConstraints=False):
            self._args[1] = ObjectIdentity(
                self._args[1]).resolveWithMib(mibViewController)

        self._state |= self.ST_CLEAM

        debug.logger & debug.FLAG_MIB and debug.logger(
            'resolved %r syntax is %r' % (self._args[0], self._args[1]))

        return self
Beispiel #23
0
    def resolveWithMib(self, mibViewController):
        """Perform MIB variable ID conversion.

        Parameters
        ----------
        mibViewController : :py:class:`~pysnmp.smi.view.MibViewController`
            class instance representing MIB browsing functionality.

        Returns
        -------
        : :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
            reference to itself

        Raises
        ------
        SmiError
           In case of fatal MIB hanling errora

        Notes
        -----
        Calling this method might cause the following sequence of
        events (exact details depends on many factors):

        * ASN.1 MIB file downloaded and handed over to
          :py:class:`~pysmi.compiler.MibCompiler` for conversion into
          Python MIB module (based on pysnmp classes)
        * Python MIB module is imported by SNMP engine, internal indices
          created
        * :py:class:`~pysnmp.smi.view.MibViewController` looks up the
          rest of MIB identification information based on whatever information
          is already available, :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity`
          class instance
          gets updated and ready for further use.

        Examples
        --------
        >>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr')
        >>> objectIdentity.resolveWithMib(mibViewController)
        ObjectIdentity('SNMPv2-MIB', 'sysDescr')
        >>>

        """
        if self.__mibSourcesToAdd is not None:
            debug.logger & debug.flagMIB and debug.logger('adding MIB sources %s' % ', '.join(self.__mibSourcesToAdd))
            mibViewController.mibBuilder.addMibSources(
                *[ZipMibSource(x) for x in self.__mibSourcesToAdd]
            )
            self.__mibSourcesToAdd = None

        if self.__asn1SourcesToAdd is None:
            addMibCompiler(mibViewController.mibBuilder,
                           ifAvailable=True, ifNotAdded=True)
        else:
            debug.logger & debug.flagMIB and debug.logger(
                'adding MIB compiler with source paths %s' % ', '.join(self.__asn1SourcesToAdd))
            addMibCompiler(
                mibViewController.mibBuilder,
                sources=self.__asn1SourcesToAdd,
                searchers=self.__asn1SourcesOptions.get('searchers'),
                borrowers=self.__asn1SourcesOptions.get('borrowers'),
                destination=self.__asn1SourcesOptions.get('destination'),
                ifAvailable=self.__asn1SourcesOptions.get('ifAvailable'),
                ifNotAdded=self.__asn1SourcesOptions.get('ifNotAdded')
            )
            self.__asn1SourcesToAdd = self.__asn1SourcesOptions = None

        if self.__modNamesToLoad is not None:
            debug.logger & debug.flagMIB and debug.logger('loading MIB modules %s' % ', '.join(self.__modNamesToLoad))
            mibViewController.mibBuilder.loadModules(*self.__modNamesToLoad)
            self.__modNamesToLoad = None

        if self.__state & self.stClean:
            return self

        MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar',
                                                                               'MibTableColumn')

        self.__indices = ()

        if isinstance(self.__args[0], ObjectIdentity):
            self.__args[0].resolveWithMib(mibViewController)

        if len(self.__args) == 1:  # OID or label or MIB module
            debug.logger & debug.flagMIB and debug.logger('resolving %s as OID or label' % self.__args)
            try:
                # pyasn1 ObjectIdentifier or sequence of ints or string OID
                self.__oid = rfc1902.ObjectName(self.__args[0])  # OID
            except PyAsn1Error:
                # sequence of sub-OIDs and labels
                if isinstance(self.__args[0], (list, tuple)):
                    prefix, label, suffix = mibViewController.getNodeName(
                        self.__args[0]
                    )
                # string label
                elif '.' in self.__args[0]:
                    prefix, label, suffix = mibViewController.getNodeNameByOid(
                        tuple(self.__args[0].split('.'))
                    )
                # MIB module name
                else:
                    modName = self.__args[0]
                    mibViewController.mibBuilder.loadModules(modName)
                    if self.__kwargs.get('last'):
                        prefix, label, suffix = mibViewController.getLastNodeName(modName)
                    else:
                        prefix, label, suffix = mibViewController.getFirstNodeName(modName)

                if suffix:
                    try:
                        suffix = tuple([int(x) for x in suffix])
                    except ValueError:
                        raise SmiError('Unknown object name component %r' % (suffix,))
                self.__oid = rfc1902.ObjectName(prefix + suffix)
            else:
                prefix, label, suffix = mibViewController.getNodeNameByOid(
                    self.__oid
                )

            debug.logger & debug.flagMIB and debug.logger(
                'resolved %r into prefix %r and suffix %r' % (self.__args, prefix, suffix))

            modName, symName, _ = mibViewController.getNodeLocation(prefix)

            self.__modName = modName
            self.__symName = symName

            self.__label = label

            mibNode, = mibViewController.mibBuilder.importSymbols(
                modName, symName
            )

            self.__mibNode = mibNode

            debug.logger & debug.flagMIB and debug.logger('resolved prefix %r into MIB node %r' % (prefix, mibNode))

            if isinstance(mibNode, MibTableColumn):  # table column
                if suffix:
                    rowModName, rowSymName, _ = mibViewController.getNodeLocation(
                        mibNode.name[:-1]
                    )
                    rowNode, = mibViewController.mibBuilder.importSymbols(
                        rowModName, rowSymName
                    )
                    self.__indices = rowNode.getIndicesFromInstId(suffix)
            elif isinstance(mibNode, MibScalar):  # scalar
                if suffix:
                    self.__indices = (rfc1902.ObjectName(suffix),)
            else:
                if suffix:
                    self.__indices = (rfc1902.ObjectName(suffix),)
            self.__state |= self.stClean

            debug.logger & debug.flagMIB and debug.logger('resolved indices are %r' % (self.__indices,))

            return self
        elif len(self.__args) > 1:  # MIB, symbol[, index, index ...]
            # MIB, symbol, index, index
            if self.__args[0] and self.__args[1]:
                self.__modName = self.__args[0]
                self.__symName = self.__args[1]
            # MIB, ''
            elif self.__args[0]:
                mibViewController.mibBuilder.loadModules(self.__args[0])
                if self.__kwargs.get('last'):
                    prefix, label, suffix = mibViewController.getLastNodeName(self.__args[0])
                else:
                    prefix, label, suffix = mibViewController.getFirstNodeName(self.__args[0])
                self.__modName, self.__symName, _ = mibViewController.getNodeLocation(prefix)
            # '', symbol, index, index
            else:
                prefix, label, suffix = mibViewController.getNodeName(self.__args[1:])
                self.__modName, self.__symName, _ = mibViewController.getNodeLocation(prefix)

            mibNode, = mibViewController.mibBuilder.importSymbols(
                self.__modName, self.__symName
            )

            self.__mibNode = mibNode

            self.__oid = rfc1902.ObjectName(mibNode.getName())

            prefix, label, suffix = mibViewController.getNodeNameByOid(
                self.__oid
            )
            self.__label = label

            debug.logger & debug.flagMIB and debug.logger(
                'resolved %r into prefix %r and suffix %r' % (self.__args, prefix, suffix))

            if isinstance(mibNode, MibTableColumn):  # table
                rowModName, rowSymName, _ = mibViewController.getNodeLocation(
                    mibNode.name[:-1]
                )
                rowNode, = mibViewController.mibBuilder.importSymbols(
                    rowModName, rowSymName
                )
                if self.__args[2:]:
                    try:
                        instIds = rowNode.getInstIdFromIndices(*self.__args[2:])
                        self.__oid += instIds
                        self.__indices = rowNode.getIndicesFromInstId(instIds)
                    except PyAsn1Error:
                        raise SmiError('Instance index %r to OID convertion failure at object %r: %s' % (
                            self.__args[2:], mibNode.getLabel(), sys.exc_info()[1]))
            elif self.__args[2:]:  # any other kind of MIB node with indices
                if self.__args[2:]:
                    instId = rfc1902.ObjectName(
                        '.'.join([str(x) for x in self.__args[2:]])
                    )
                    self.__oid += instId
                    self.__indices = (instId,)
            self.__state |= self.stClean

            debug.logger & debug.flagMIB and debug.logger('resolved indices are %r' % (self.__indices,))

            return self
        else:
            raise SmiError('Non-OID, label or MIB symbol')
Beispiel #24
0
 def getMibNode(self):
     if self.__state & self.stClean:
         return self.__mibNode
     else:
         raise SmiError('%s object not fully initialized' % self.__class__.__name__)
Beispiel #25
0
def getTargetAddr(snmpEngine, snmpTargetAddrName):
    mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

    snmpTargetAddrEntry, = mibBuilder.importSymbols(
        'SNMP-TARGET-MIB', 'snmpTargetAddrEntry'
    )

    cache = snmpEngine.getUserContext('getTargetAddr')
    if cache is None:
        cache = {'id': -1}
        snmpEngine.setUserContext(getTargetAddr=cache)

    if cache['id'] != snmpTargetAddrEntry.branchVersionId:
        cache['nameToTargetMap'] = {}

    nameToTargetMap = cache['nameToTargetMap']

    if snmpTargetAddrName not in nameToTargetMap:
        (snmpTargetAddrTDomain,
         snmpTargetAddrTAddress,
         snmpTargetAddrTimeout,
         snmpTargetAddrRetryCount,
         snmpTargetAddrParams) = mibBuilder.importSymbols(
            'SNMP-TARGET-MIB', 'snmpTargetAddrTDomain',
            'snmpTargetAddrTAddress', 'snmpTargetAddrTimeout',
            'snmpTargetAddrRetryCount', 'snmpTargetAddrParams'
        )
        snmpSourceAddrTAddress, = mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrTAddress')

        tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(snmpTargetAddrName)

        try:
            snmpTargetAddrTDomain = snmpTargetAddrTDomain.getNode(
                snmpTargetAddrTDomain.name + tblIdx
            ).syntax
            snmpTargetAddrTAddress = snmpTargetAddrTAddress.getNode(
                snmpTargetAddrTAddress.name + tblIdx
            ).syntax
            snmpTargetAddrTimeout = snmpTargetAddrTimeout.getNode(
                snmpTargetAddrTimeout.name + tblIdx
            ).syntax
            snmpTargetAddrRetryCount = snmpTargetAddrRetryCount.getNode(
                snmpTargetAddrRetryCount.name + tblIdx
            ).syntax
            snmpTargetAddrParams = snmpTargetAddrParams.getNode(
                snmpTargetAddrParams.name + tblIdx
            ).syntax
            snmpSourceAddrTAddress = snmpSourceAddrTAddress.getNode(
                snmpSourceAddrTAddress.name + tblIdx
            ).syntax
        except NoSuchInstanceError:
            raise SmiError('Target %s not configured to LCD' % snmpTargetAddrName)

        transport = snmpEngine.transportDispatcher.getTransport(snmpTargetAddrTDomain)

        if snmpTargetAddrTDomain[:len(config.snmpUDPDomain)] == config.snmpUDPDomain:
            SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM',
                                                                                                    'SnmpUDPAddress')
            snmpTargetAddrTAddress = transport.addressType(
                SnmpUDPAddress(snmpTargetAddrTAddress)
            ).setLocalAddress(SnmpUDPAddress(snmpSourceAddrTAddress))
        elif snmpTargetAddrTDomain[:len(config.snmpUDP6Domain)] == config.snmpUDP6Domain:
            TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols(
                'TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6')
            snmpTargetAddrTAddress = transport.addressType(
                TransportAddressIPv6(snmpTargetAddrTAddress)
            ).setLocalAddress(TransportAddressIPv6(snmpSourceAddrTAddress))
        elif snmpTargetAddrTDomain[:len(config.snmpLocalDomain)] == config.snmpLocalDomain:
            snmpTargetAddrTAddress = transport.addressType(
                snmpTargetAddrTAddress
            )

        nameToTargetMap[snmpTargetAddrName] = (
            snmpTargetAddrTDomain,
            snmpTargetAddrTAddress,
            snmpTargetAddrTimeout,
            snmpTargetAddrRetryCount,
            snmpTargetAddrParams
        )

        cache['id'] = snmpTargetAddrEntry.branchVersionId

    return nameToTargetMap[snmpTargetAddrName]