コード例 #1
0
ファイル: snmpclient.py プロジェクト: rpuligandla/csr
    def setCmd(self, agent, context, host, port, *varBinds):
        self._setup(agent, context, host, port)

        ## @brief call back function
        # @param sendRequestHandle
        # @param errorIndication indicates error
        # @param errorStatus status of error
        # @param errorIndex index of error
        # @param varBinds variable bindings (sequence)
        # @param cbCtx application state
        # @returns cbCtx application state
        def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
                  varBinds, cbCtx):
            cbCtx['errorIndication'] = errorIndication
            cbCtx['errorStatus'] = errorStatus
            cbCtx['errorIndex'] = errorIndex
            cbCtx['varBinds'] = varBinds

        cbCtx = {}

        __varBinds = []
        for varName, varVal in varBinds:
            __varBinds.append((varName, varVal))

        cmdgen.SetCommandGenerator().sendReq(self.snmpEngine, 'myRouter',
                                             __varBinds, cbFun, cbCtx)

        self.snmpEngine.transportDispatcher.runDispatcher()
        #the 'getColumn' SNMP command
        return (cbCtx['errorIndication'], cbCtx['errorStatus'],
                cbCtx['errorIndex'], cbCtx['varBinds'])
コード例 #2
0
    def setCmd(self,
               authData,
               transportTarget,
               varBinds,
               cbInfo,
               lookupNames=False,
               lookupValues=False,
               contextEngineId=None,
               contextName=null):
        def __cbFun(sendRequestHandle, errorIndication, errorStatus,
                    errorIndex, varBinds, cbCtx):
            lookupNames, lookupValues, cbFun, cbCtx = cbCtx
            return cbFun(
                sendRequestHandle, errorIndication, errorStatus, errorIndex,
                self.unmakeVarBinds(varBinds, lookupNames, lookupValues),
                cbCtx)

        # for backward compatibility
        if contextName is null and authData.contextName:
            contextName = authData.contextName

        (cbFun, cbCtx) = cbInfo
        addrName, paramsName = self.cfgCmdGen(authData, transportTarget)

        return cmdgen.SetCommandGenerator().sendReq(
            self.snmpEngine, addrName, self.makeVarBinds(varBinds), __cbFun,
            (lookupNames, lookupValues, cbFun, cbCtx), contextEngineId,
            contextName)
コード例 #3
0
    def setCmd(self, authData, transportTarget, varBinds, cbInfo):
        (cbFun, cbCtx) = cbInfo
        addrName, paramsName = self.cfgCmdGen(authData, transportTarget)
        __varBinds = []
        for varName, varVal in varBinds:
            if isinstance(varName, MibVariable):
                varName.resolveWithMib(self.mibViewController)
                if not isinstance(varVal, base.AbstractSimpleAsn1Item):
                    varVal = varName.getMibNode().getSyntax().clone(varVal)
            elif isinstance(varName[0], tuple):  # legacy
                varName = MibVariable(varName[0][0], varName[0][1],
                                      *varName[1:]).resolveWithMib(
                                          self.mibViewController)
                if not isinstance(varVal, base.AbstractSimpleAsn1Item):
                    varVal = varName.getMibNode().getSyntax().clone(varVal)
            else:
                if isinstance(varVal, base.AbstractSimpleAsn1Item):
                    varName = MibVariable(varName).resolveWithMib(
                        self.mibViewController, oidOnly=True)
                else:
                    varName = MibVariable(varName).resolveWithMib(
                        self.mibViewController)
                    varVal = varName.getMibNode().getSyntax().clone(varVal)

            __varBinds.append((varName, varVal))
        return cmdgen.SetCommandGenerator().sendReq(self.snmpEngine, addrName,
                                                    __varBinds, cbFun, cbCtx,
                                                    authData.contextEngineId,
                                                    authData.contextName)
コード例 #4
0
ファイル: snmp.py プロジェクト: sohonet/HEN
    def complex_set(self, value):
        log.info("snmpset " + self.printOptions() + " " +
                 str(self.printSetList(value)))

        def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
                  varBinds, cbCtx):
            cbCtx['errorIndication'] = errorIndication
            cbCtx['errorStatus'] = errorStatus
            cbCtx['errorIndex'] = errorIndex
            cbCtx['varBinds'] = varBinds

        cb = {}
        #self.__lock.acquire()
        #cmdgen.SetCommandGenerator().sendReq(self.__snmp_engine, 'myRouter', ((value, None),), cbFun, cb)
        try:
            cmdgen.SetCommandGenerator().sendReq(self.__snmp_engine,
                                                 'myRouter', value, cbFun, cb)
            self.__snmp_engine.transportDispatcher.runDispatcher()
            #self.__lock.release()
            self.__errorIndication = cb['errorIndication']
            self.__errorStatus = cb['errorStatus']
            self.__errorIndex = cb['errorIndex']
            self.__varBinds = cb['varBinds']
        except Exception, e:
            log.debug(e)
            self.__errorIndication = "crash"
            self.__errorStatus = 1
コード例 #5
0
ファイル: snmp_client.py プロジェクト: xushuo1/conpot
 def set_command(self, OID, callback=None):
     if not callback:
         callback = self.cbFun
     cmdgen.SetCommandGenerator().sendReq(
         self.snmpEngine, "my-router", (OID,), callback,
     )
     self.snmpEngine.transportDispatcher.runDispatcher()
コード例 #6
0
ファイル: snmp_client.py プロジェクト: firebitsbr/conpot
 def set_command(self, OID, callback=None):
     if not callback:
         callback = self.cbFun
     cmdgen.SetCommandGenerator().sendReq(
         self.snmpEngine,
         'my-router',
         (OID, ),
         callback,
     )
コード例 #7
0
    def send_set_var_binds(self, oids):
        cmd_gen = cmdgen.SetCommandGenerator()

        cmd_gen.sendVarBinds(
            self._snmp_engine,
            "tgt",
            self._context_id,
            self._context_name,
            oids,
            self.cb_fun,
            self.cb_ctx,
        )
コード例 #8
0
class CommandResponder(cmdrsp.CommandResponderBase):
    cmdGenMap = { 
        v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(),
        v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(),
        v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(),
        v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun() 
    }
    pduTypes = cmdGenMap.keys()  # This app will handle these PDUs

    # SNMP request relay
    def handleMgmtOperation(self, snmpEngine, stateReference, contextName,
                            PDU, acInfo):
        cbCtx = snmpEngine, stateReference
        varBinds = v2c.apiPDU.getVarBinds(PDU)
        try:
            if PDU.tagSet == v2c.GetBulkRequestPDU.tagSet:
                self.cmdGenMap[PDU.tagSet].sendReq(
                    snmpEngine, 'distant-agent', 
                    v2c.apiBulkPDU.getNonRepeaters(PDU),
                    v2c.apiBulkPDU.getMaxRepetitions(PDU),
                    varBinds,
                    self.handleResponse, cbCtx
                )
            elif PDU.tagSet in self.cmdGenMap:
                self.cmdGenMap[PDU.tagSet].sendReq(
                    snmpEngine, 'distant-agent', varBinds,
                    self.handleResponse, cbCtx
                )
        except error.PySnmpError:
            self.handleResponse(
                stateReference,  'error', 0, 0, varBinds, cbCtx
            )

    # SNMP response relay
    def handleResponse(self, sendRequestHandle, errorIndication, 
                       errorStatus, errorIndex, varBinds, cbCtx):
        if errorIndication:
            errorStatus = 5
            errorIndex = 0
            varBinds = ()

        snmpEngine, stateReference = cbCtx

        self.sendRsp(
            snmpEngine, stateReference,  errorStatus, errorIndex, varBinds
        )
コード例 #9
0
ファイル: agentproxy.py プロジェクト: shivram2609/twistedsnmp
    def set(self, oids, timeout=2.0, retryCount=4):
        """Set a variable on our connected agent

		oids -- dictionary of oid:value pairs, or a list of
			(oid,value) tuples to be set on the agent

		raises errors if the setting fails
		"""
        df = defer.Deferred()
        cmdgen.SetCommandGenerator().sendReq(
            self.engine,
            self.targetName,
            oids,
            self._onSetResult,
            df,
        )
        return df
コード例 #10
0
class CommandResponder(cmdrsp.CommandResponderBase):
    CMDGEN_MAP = {
        v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(),
        v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(),
        v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(),
        v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun()
    }
    SUPPORTED_PDU_TYPES = tuple(CMDGEN_MAP)  # This app will handle these PDUs

    # SNMP request relay
    def handleMgmtOperation(self, snmpEngine, stateReference, contextName,
                            PDU, acInfo):
        cbCtx = stateReference, PDU
        contextEngineId = None  # address authoritative SNMP Engine
        try:
            self.CMDGEN_MAP[PDU.tagSet].sendPdu(
                snmpEngine, 'distant-agent',
                contextEngineId, contextName,
                PDU,
                self.handleResponsePdu, cbCtx
            )

        except error.PySnmpError:
            self.handleResponsePdu(
                snmpEngine, stateReference, 'error', None, cbCtx
            )

    # SNMP response relay
    # noinspection PyUnusedLocal
    def handleResponsePdu(self, snmpEngine, sendRequestHandle,
                          errorIndication, PDU, cbCtx):
        stateReference, reqPDU = cbCtx

        if errorIndication:
            PDU = v2c.apiPDU.getResponse(reqPDU)
            PDU.setErrorStatus(PDU, 5)

        self.sendPdu(
            snmpEngine, stateReference, PDU
        )

        self.releaseStateInformation(stateReference)
コード例 #11
0
ファイル: snmp.py プロジェクト: sohonet/HEN
    def set(self, oid, value):
        #log.info("snmpset "+self.printOptions()+str(oid.prettyPrint())+" "+self.getSnmpValueType(value))
        def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
                  varBinds, cbCtx):
            cbCtx['errorIndication'] = errorIndication
            cbCtx['errorStatus'] = errorStatus
            cbCtx['errorIndex'] = errorIndex
            cbCtx['varBinds'] = varBinds

        cb = {}
        #self.__lock.acquire()
        cmdgen.SetCommandGenerator().sendReq(self.__snmp_engine, 'myRouter',
                                             ((oid, value), ), cbFun, cb)
        self.__snmp_engine.transportDispatcher.runDispatcher()
        #self.__lock.release()
        self.__errorIndication = cb['errorIndication']
        self.__errorStatus = cb['errorStatus']
        self.__errorIndex = cb['errorIndex']
        self.__varBinds = cb['varBinds']

        #self.__snmp_engine.transportDispatcher().closeDispatcher()
        if self.getErrorStatus():
            log.critical("Error in snmp set " + str(self.showError()))
        return self.__varBinds
コード例 #12
0
ファイル: snmpset.py プロジェクト: tjtunnell/pysnmp-apps
try:
    # Parse c/l into AST
    ast = Parser().parse(Scanner().tokenize(' '.join(sys.argv[1:])))

    ctx = {}

    # Apply configuration to SNMP entity
    main.generator((snmpEngine, ctx), ast)
    msgmod.generator((snmpEngine, ctx), ast)
    secmod.generator((snmpEngine, ctx), ast)
    mibview.generator((snmpEngine, ctx), ast)
    target.generator((snmpEngine, ctx), ast)
    pdu.writePduGenerator((snmpEngine, ctx), ast)

    cmdgen.SetCommandGenerator().sendVarBinds(snmpEngine, ctx['addrName'],
                                              ctx.get('contextEngineId'),
                                              ctx.get('contextName', ''),
                                              ctx['varBinds'], cbFun, ctx)

    snmpEngine.transportDispatcher.runDispatcher()

except KeyboardInterrupt:
    sys.stderr.write('Shutting down...\n')

except error.PySnmpError:
    sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage()))
    sys.exit(-1)

except Exception:
    sys.stderr.write('Process terminated: %s\n' % sys.exc_info()[1])
    for line in traceback.format_exception(*sys.exc_info()):
        sys.stderr.write(line.replace('\n', ';'))
コード例 #13
0
def setCmd(snmpEngine, authData, transportTarget, contextData,
           *varBinds, **options):
    """Performs SNMP SET query.

    Based on passed parameters, prepares SNMP SET packet
    (:RFC:`1905#section-4.2.5`) and schedules its transmission by
    :mod:`twisted` I/O framework at a later point of time.

    Parameters
    ----------
    snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine`
        Class instance representing SNMP engine.

    authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData`
        Class instance representing SNMP credentials.

    transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget`
        Class instance representing transport type along with SNMP peer address.

    contextData : :class:`~pysnmp.hlapi.ContextData`
        Class instance representing SNMP ContextEngineId and ContextName values.

    \*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType`
        One or more class instances representing MIB variables to place
        into SNMP request.

    Other Parameters
    ----------------
    \*\*options :
        Request options:

            * `lookupMib` - load MIB and resolve response MIB variables at
              the cost of slightly reduced performance. Default is `True`.

    Returns
    -------
    deferred : :class:`~twisted.internet.defer.Deferred`
        Twisted Deferred object representing work-in-progress. User
        is expected to attach his own `success` and `error` callback
        functions to the Deferred object though
        :meth:`~twisted.internet.defer.Deferred.addCallbacks` method.

    Raises
    ------
    PySnmpError
        Or its derivative indicating that an error occurred while
        performing SNMP operation.

    Notes
    -----
    User `success` callback is called with the following tuple as
    its first argument:

    * errorStatus (str) : True value indicates SNMP PDU error.
    * errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]`
    * varBinds (tuple) : A sequence of
      :class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing
      MIB variables returned in SNMP response.

    User `error` callback is called with `errorIndication` object wrapped
    in :class:`~twisted.python.failure.Failure` object.

    Examples
    --------
    >>> from twisted.internet.task import react
    >>> from pysnmp.hlapi.twisted import *
    >>>
    >>> def success(args):
    ...     (errorStatus, errorIndex, varBinds) = args
    ...     print(errorStatus, errorIndex, varBind)
    ...
    >>> def failure(errorIndication):
    ...     print(errorIndication)
    ...
    >>> def run(reactor):
    ...     d = setCmd(SnmpEngine(),
    ...                CommunityData('public'),
    ...                UdpTransportTarget(('demo.snmplabs.com', 161)),
    ...                ContextData(),
    ...                ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386')
    ...     d.addCallback(success).addErrback(failure)
    ...     return d
    ...
    >>> react(run)
    (0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('Linux i386'))])
    >>>

    """
    def __cbFun(snmpEngine, sendRequestHandle,
                errorIndication, errorStatus, errorIndex,
                varBinds, cbCtx):
        lookupMib, deferred = cbCtx
        if errorIndication:
            deferred.errback(Failure(errorIndication))
        else:
            try:
                varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine.cache, varBinds, lookupMib)

            except Exception as e:
                deferred.errback(Failure(e))

            else:
                deferred.callback((errorStatus, errorIndex, varBindsUnmade))

    addrName, paramsName = lcd.configure(
        snmpEngine, authData, transportTarget, contextData.contextName)

    deferred = Deferred()

    cmdgen.SetCommandGenerator().sendVarBinds(
        snmpEngine, addrName, contextData.contextEngineId,
        contextData.contextName,
        vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
        (options.get('lookupMib', True), deferred)
    )
    return deferred
コード例 #14
0
class CommandResponder(cmdrsp.CommandResponderBase):
    cmdGenMap = {
        v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(),
        v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(),
        v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(),
        v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun()
    }
    pduTypes = cmdGenMap.keys()  # This app will handle these PDUs

    # SNMP request relay
    def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU,
                            acInfo):
        cbCtx = snmpEngine, stateReference
        varBinds = v2c.apiPDU.getVarBinds(PDU)
        print "Begin of handleMgmtOperation"

        try:
            if contextName not in agentMap:
                raise PySnmpError('Unknown context name %s' % contextName)

            # Select backend Agent ID by contextName arrived with request
            targetName, targetAddress = agentMap[contextName]
            isCached = 1
            indice = 0
            print "Beginning to check all of cache"
            for oid in varBinds:
                k, v = oid
                key = targetAddress + "-" + str(oid[0])
                print "Checking cache for oid: " + str(oid[0])
                if r.exists(key) == True:
                    v = r.get(key)
                    varBinds[indice] = (k, v)
                    indice = indice + 1
                    print "Key Cached: " + str(k)
                    #self.sendRsp(snmpEngine, stateReference,  0, 0, varBinds)
                else:
                    isCached = 0
                    print "Not all entries cached: " + str(k)
                    #break

            if isCached == 1:
                print "All cached - sending cached response"
                self.sendRsp(snmpEngine, stateReference, 0, 0, varBinds)
            elif isCached == 0:
                print "Not all cached - sending request"
                if PDU.tagSet == v2c.GetBulkRequestPDU.tagSet:
                    self.cmdGenMap[PDU.tagSet].sendReq(
                        snmpEngine, targetName,
                        v2c.apiBulkPDU.getNonRepeaters(PDU),
                        v2c.apiBulkPDU.getMaxRepetitions(PDU), varBinds,
                        self.handleResponse, cbCtx)
                elif PDU.tagSet in self.cmdGenMap:
                    self.cmdGenMap[PDU.tagSet].sendReq(snmpEngine, targetName,
                                                       varBinds,
                                                       self.handleResponse,
                                                       cbCtx)
        except error.PySnmpError:
            print sys.exc_info()[1]
            self.handleResponse(stateReference, 'error', 0, 0, varBinds, cbCtx)

    # SNMP response relay
    def handleResponse(self, sendRequestHandle, errorIndication, errorStatus,
                       errorIndex, varBinds, cbCtx):
        if errorIndication:
            errorStatus = 5
            errorIndex = 0
            varBinds = ()

        snmpEngine, stateReference = cbCtx
        hosts = snmpEngine.cache['getTargetAddr']['nameToTargetMap']
        host = ""
        for key in hosts.items():
            k, v = key
            host = v[1][0]
        for a in varBinds:
            key = str(host) + "-" + str(a[0])
            print "Caching Key: " + key
            r.setex(key, 120, a[1])
        print "Sending uncached response to client"
        self.sendRsp(snmpEngine, stateReference, errorStatus, errorIndex,
                     varBinds)
コード例 #15
0
ファイル: cmdgen.py プロジェクト: jiuzhuaxiong/pysnmp
def setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds,
           **options):
    """Performs SNMP SET query.

    Based on passed parameters, prepares SNMP SET packet
    (:RFC:`1905#section-4.2.5`) and schedules its transmission by
    I/O framework at a later point of time.

    Parameters
    ----------
    snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine`
        Class instance representing SNMP engine.

    authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
        Class instance representing SNMP credentials.

    transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
        Class instance representing transport type along with SNMP peer
        address.

    contextData : :py:class:`~pysnmp.hlapi.ContextData`
        Class instance representing SNMP ContextEngineId and ContextName
        values.

    \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
        One or more class instances representing MIB variables to place
        into SNMP request.

    Other Parameters
    ----------------
    \*\*options :
        Request options:

            * `lookupMib` - load MIB and resolve response MIB variables at
              the cost of slightly reduced performance. Default is `True`.
            * `cbFun` (callable) - user-supplied callable that is invoked
               to pass SNMP response data or error to user at a later point
               of time. Default is `None`.
            * `cbCtx` (object) - user-supplied object passing additional
               parameters to/from `cbFun`. Default is `None`.

    Notes
    -----
    User-supplied `cbFun` callable must have the following call
    signature:

    * snmpEngine (:py:class:`~pysnmp.hlapi.SnmpEngine`):
      Class instance representing SNMP engine.
    * sendRequestHandle (int): Unique request identifier. Can be used
      for matching multiple ongoing requests with received responses.
    * errorIndication (str): True value indicates SNMP engine error.
    * errorStatus (str): True value indicates SNMP PDU error.
    * errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]`
    * varBinds (tuple): A sequence of
      :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
      representing MIB variables returned in SNMP response in exactly
      the same order as `varBinds` in request.
    * `cbCtx` : Original user-supplied object.

    Returns
    -------
    sendRequestHandle : int
        Unique request identifier. Can be used for matching received
        responses with ongoing requests.

    Raises
    ------
    PySnmpError
        Or its derivative indicating that an error occurred while
        performing SNMP operation.

    Examples
    --------
    >>> from pysnmp.hlapi.asyncore import *
    >>> def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx):
    ...     print(errorIndication, errorStatus, errorIndex, varBinds)
    >>>
    >>> snmpEngine = SnmpEngine()
    >>> setCmd(snmpEngine,
    ...        CommunityData('public'),
    ...        UdpTransportTarget(('demo.snmplabs.com', 161)),
    ...        ContextData(),
    ...        ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysContact', 0), '*****@*****.**'),
    ...        cbFun=cbFun)
    >>> snmpEngine.transportDispatcher.runDispatcher()
    (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.4.0')), DisplayString('*****@*****.**'))])
    >>>

    """
    def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus,
                errorIndex, varBinds, cbCtx):
        lookupMib, cbFun, cbCtx = cbCtx
        return cbFun(
            snmpEngine, sendRequestHandle, errorIndication, errorStatus,
            errorIndex,
            vbProcessor.unmakeVarBinds(snmpEngine.cache, varBinds,
                                       lookupMib), cbCtx)

    addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget,
                                         contextData.contextName)

    return cmdgen.SetCommandGenerator().sendVarBinds(
        snmpEngine, addrName, contextData.contextEngineId,
        contextData.contextName,
        vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
        (options.get('lookupMib',
                     True), options.get('cbFun'), options.get('cbCtx')))
コード例 #16
0
# UDP/IPv4
config.addSocketTransport(snmpEngine, udp.domainName,
                          udp.UdpSocketTransport().openClientMode())
config.addTargetAddr(snmpEngine, 'my-router', udp.domainName,
                     ('10.101.0.221', 161), 'private')


# Error/response reciever
def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBindTable, cbCtx):
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?'))
    else:
        for oid, val in varBindTable:
            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))


# Prepare and send a request message
cmdgen.SetCommandGenerator().sendReq(
    snmpEngine, 'my-router', (((1, 3, 6, 1, 2, 1, 31, 1, 1, 1, 18, 1),
                               rfc1902.OctetString('Check this out')), ),
    cbFun)

# Run I/O dispatcher which would send pending queries and process responses
snmpEngine.transportDispatcher.runDispatcher()
コード例 #17
0
    udp.domainName, ('195.218.195.228', 161),
    'my-creds'
)

# Error/response receiver
def cbFun(sendRequestHandle,
          errorIndication, errorStatus, errorIndex,
          varBinds, cbCtx):
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBinds[int(errorIndex)-1][0] or '?'
            )
        )
    else:
        for oid, val in varBinds:
            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))

# Prepare and send a request message
cmdgen.SetCommandGenerator().sendReq(
    snmpEngine,
    'my-router',
    ( ((1,3,6,1,2,1,1,9,1,4,1), rfc1902.TimeTicks(123)), ),
    cbFun
)

# Run I/O dispatcher which would send pending queries and process responses
snmpEngine.transportDispatcher.runDispatcher()
コード例 #18
0
ファイル: usm-sha-none.py プロジェクト: zxx1819/pysnmp

# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus,
          errorIndex, varBinds, cbCtx):
    if errorIndication:
        print(errorIndication)

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

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


# Prepare and send a request message
cmdgen.SetCommandGenerator().sendVarBinds(
    snmpEngine,
    'my-router',
    None,
    '',  # contextEngineId, contextName
    [((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString('my new value'))],
    cbFun)

# Run I/O dispatcher which would send pending queries and process responses
snmpEngine.transportDispatcher.runDispatcher()
コード例 #19
0
def snmpv3_set(ip='',
               user='',
               hash_meth=None,
               hash_key=None,
               cry_meth=None,
               cry_key=None,
               oid='',
               customerString=''):
    #usmHMACMD5AuthProtocol - MD5 hashing
    #usmHMACSHAAuthProtocol - SHA hashing
    #usmNoAuthProtocol - no authentication
    #usmDESPrivProtocol - DES encryption
    #usm3DESEDEPrivProtocol - triple-DES encryption
    #usmAesCfb128Protocol - AES encryption, 128-bit
    #usmAesCfb192Protocol - AES encryption, 192-bit
    #usmAesCfb256Protocol - AES encryption, 256-bit
    #usmNoPrivProtocol - no encryption
    hashval = None
    cryval = None
    model = None

    config.addTargetAddr(snmpEngine, 'yourDevice', udp.domainName, (ip, 161),
                         'my-creds')
    #NoAuthNoPriv
    if hash_meth == None and cry_meth == None:
        hashval = config.usmNoAuthProtocol
        cryval = config.usmNoPrivProtocol
        model = 'noAuthNoPriv'
    #AuthNoPriv
    elif hash_meth != None and cry_meth == None:
        if hash_meth == 'md5':
            hashval = config.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = config.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        cryval = config.usmNoPrivProtocol
        model = 'authNoPriv'
    #AuthPriv
    elif hash_meth != None and cry_meth != None:
        if hash_meth == 'md5':
            hashval = config.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = config.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        if cry_meth == '3des':
            cryval = config.usm3DESEDEPrivProtocol
        elif cry_meth == 'des':
            cryval = config.usmDESPrivProtocol
        elif cry_meth == 'aes128':
            cryval = config.usmAesCfb128Protocol
        elif cry_meth == 'aes192':
            cryval = config.usmAesCfb192Protocol
        elif cry_meth == 'aes256':
            cryval = config.usmAesCfb256Protocol
        else:
            print('加密算法必须是3des, des, aes128, aes192 or aes256 !')
            return
        model = 'authPriv'
    #提供的参数不符合标准时给出提示
    else:
        print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。')
        return

    config.addV3User(snmpEngine, user, hashval, hash_key, cryval, cry_key)
    config.addTargetParams(snmpEngine, 'my-creds', user, model)

    # Prepare and send a request message
    cmdgen.SetCommandGenerator().sendReq(
        snmpEngine,
        'yourDevice',
        ((oid, rfc1902.OctetString(customerString)), ),  #oid与要设置的值
        cbFun)

    # Run I/O dispatcher which would send pending queries and process responses
    snmpEngine.transportDispatcher.runDispatcher()
コード例 #20
0
config.addTargetAddr(snmpEngine, 'my-router', udp.domainName,
                     ('104.236.166.95', 161), 'my-creds')


# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus,
          errorIndex, varBinds, cbCtx):
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        for oid, val in varBinds:
            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))


# Prepare and send a request message
cmdgen.SetCommandGenerator().sendVarBinds(
    snmpEngine,
    'my-router',
    None,
    '',  # contextEngineId, contextName
    [((1, 3, 6, 1, 2, 1, 1, 9, 1, 4, 1), rfc1902.TimeTicks(123))],
    cbFun)

# Run I/O dispatcher which would send pending queries and process responses
snmpEngine.transportDispatcher.runDispatcher()
コード例 #21
0
def snmpv3_set(ip='', user='', hash_meth=None, hash_key=None, cry_meth=None, cry_key=None, oid='', customer_string=''):
    # usmHMACMD5AuthProtocol - MD5 hashing
    # usmHMACSHAAuthProtocol - SHA hashing
    # usmNoAuthProtocol - no authentication
    # usmDESPrivProtocol - DES encryption
    # usm3DESEDEPrivProtocol - triple-DES encryption
    # usmAesCfb128Protocol - AES encryption, 128-bit
    # usmAesCfb192Protocol - AES encryption, 192-bit
    # usmAesCfb256Protocol - AES encryption, 256-bit
    # usmNoPrivProtocol - no encryption

    # 添加目标,'yourDevice'(OID与处理方法),'my-creds'(用户,密码,安全模型),目的IP与端口号
    config.addTargetAddr(snmpEngine, 'yourDevice', udp.domainName, (ip, 161), 'my-creds')
    # ========================下面的操作在判断安全模型==========================
    # NoAuthNoPriv
    if hash_meth is None and cry_meth is None:
        hashval = config.usmNoAuthProtocol  # 配置HASH算法
        cryval = config.usmNoPrivProtocol  # 配置加密算法
        model = 'noAuthNoPriv'  # 配置安全模式
    # AuthNoPriv
    elif hash_meth is not None and cry_meth is None:
        # 配置HASH算法
        if hash_meth == 'md5':
            hashval = config.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = config.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        cryval = config.usmNoPrivProtocol  # 配置加密算法
        model = 'authNoPriv'  # 配置安全模式
    # AuthPriv
    elif hash_meth is not None and cry_meth is not None:
        # 配置HASH算法
        if hash_meth == 'md5':
            hashval = config.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = config.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        # 配置加密算法
        if cry_meth == '3des':
            cryval = config.usm3DESEDEPrivProtocol
        elif cry_meth == 'des':
            cryval = config.usmDESPrivProtocol
        elif cry_meth == 'aes128':
            cryval = config.usmAesCfb128Protocol
        elif cry_meth == 'aes192':
            cryval = config.usmAesCfb192Protocol
        elif cry_meth == 'aes256':
            cryval = config.usmAesCfb256Protocol
        else:
            print('加密算法必须是3des, des, aes128, aes192 or aes256 !')
            return
        model = 'authPriv'  # 配置安全模式
    # 提供的参数不符合标准时给出提示
    else:
        print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。')
        return
    # ========================判断安全模型结束==========================
    # 添加用户与他的密钥
    config.addV3User(snmpEngine, user, hashval, hash_key, cryval, cry_key)
    config.addTargetParams(snmpEngine, 'my-creds', user, model)  # 创建'my-creds',里边有用户和安全模型

    # Prepare and send a request message
    # 创建'yourDevice',有OID和处理方法cbFun
    if isinstance(customer_string, str):
        set_value = rfc1902.OctetString(customer_string)
    elif isinstance(customer_string, int):
        set_value = rfc1902.Integer(customer_string)

    cmdgen.SetCommandGenerator().sendReq(snmpEngine, 'yourDevice', ((oid, set_value),), cb_fun)

    # Run I/O dispatcher which would send pending queries and process responses
    snmpEngine.transportDispatcher.runDispatcher()  # 运行实例
コード例 #22
0
# UDP/IPv4
config.addTransport(snmpEngine, udp.domainName,
                    udp.UdpSocketTransport().openClientMode())
config.addTargetAddr(snmpEngine, 'my-router', udp.domainName,
                     ('195.218.195.228', 161), 'my-creds')


# Error/response receiver
def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBinds, cbCtx):
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        for oid, val in varBinds:
            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))


# Prepare and send a request message
cmdgen.SetCommandGenerator().sendReq(snmpEngine, 'my-router',
                                     (((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1),
                                       rfc1902.OctetString('my new value')), ),
                                     cbFun)

# Run I/O dispatcher which would send pending queries and process responses
snmpEngine.transportDispatcher.runDispatcher()
コード例 #23
0
ファイル: setgen.py プロジェクト: rlaneyjr/cheaters
    snmpEngine,
    udp.domainName,
    udp.UdpSocketTransport().openClientMode()
    )

def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBinds, cbCtx):
    cbCtx['errorIndication'] = errorIndication
    cbCtx['errorStatus'] = errorStatus
    cbCtx['errorIndex'] = errorIndex
    cbCtx['varBinds'] = varBinds

cbCtx = {}

cmdgen.SetCommandGenerator().sendReq(
    snmpEngine, 'myRouter',
    (((1,3,6,1,2,1,1,1,0), rfc1902.OctetString('Grinch')),), cbFun, cbCtx
    )

snmpEngine.transportDispatcher.runDispatcher()
if cbCtx['errorIndication']:
    print cbCtx['errorIndication']
elif cbCtx['errorStatus']:
    print '%s at %s' % (
        cbCtx['errorStatus'].prettyPrint(),
        cbCtx['varBinds'][int(cbCtx['errorIndex'])-1]
        )
else:
    for o, v in cbCtx['varBinds']:
        print '%s = %s' % (o.prettyPrint(), v.prettyPrint())
コード例 #24
0
ファイル: cmdgen.py プロジェクト: delian/testerman
        addrName, paramsName = self.cfgCmdGen(authData, transportTarget)
        __varBinds = []
        for varName, varVal in varBinds:
            name, oid = mibvar.mibNameToOid(self.mibViewController, varName)
            if not type(varVal) == types.InstanceType:
                ((symName, modName),
                 suffix) = mibvar.oidToMibName(self.mibViewController,
                                               name + oid)
                syntax = mibvar.cloneFromMibValue(self.mibViewController,
                                                  modName, symName, varVal)
                if syntax is None:
                    raise error.PySnmpError(
                        'Value type MIB lookup failed for %s' % repr(varName))
                varVal = syntax.clone(varVal)
            __varBinds.append((name + oid, varVal))
        return cmdgen.SetCommandGenerator().sendReq(self.snmpEngine, addrName,
                                                    __varBinds, cbFun, cbCtx)

    def asyncNextCmd(self, authData, transportTarget, varNames, (cbFun,
                                                                 cbCtx)):
        addrName, paramsName = self.cfgCmdGen(authData, transportTarget)
        varBinds = []
        for varName in varNames:
            name, oid = mibvar.mibNameToOid(self.mibViewController, varName)
            varBinds.append((name + oid, self._null))
        return cmdgen.NextCommandGenerator().sendReq(self.snmpEngine, addrName,
                                                     varBinds, cbFun, cbCtx)

    def asyncBulkCmd(self, authData, transportTarget, nonRepeaters,
                     maxRepetitions, varNames, (cbFun, cbCtx)):
        addrName, paramsName = self.cfgCmdGen(authData, transportTarget)
        varBinds = []
コード例 #25
0
ファイル: snmp_alert_set.py プロジェクト: anlaneg/pyghmi

# Error/response reciever
def set_trap_target_addr_cb(sendRequestHandle,
          errorIndication, errorStatus, errorIndex,
          varBindTable, cbCtx):
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
            )
        )
    else:
        for oid, val in varBindTable:
            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))

# Prepare and send a request message
#set trap target is '1.1.1.1'
# .1.3.6.1.4.1.2011.2.235.1.1.4.50.1.3.1 s "10.100.206.223"
cmdgen.SetCommandGenerator().sendReq(
    snmpEngine,
    'my-router',
    ( (( 1,3,6,1,4,1,2011,2,235,1,1,4,50,1,3,1), rfc1902.OctetString('10.100.206.223')), ),
    set_trap_target_addr_cb
)

# Run I/O dispatcher which would send pending queries and process responses
snmpEngine.transportDispatcher.runDispatcher()
コード例 #26
0
def setCmd(snmpEngine, authData, transportTarget, contextData,
           *varBinds, **options):
    """Creates a generator to perform SNMP SET query.

    When itereator gets advanced by :py:mod:`asyncio` main loop,
    SNMP SET request is send (:RFC:`1905#section-4.2.5`).
    The iterator yields :py:class:`asyncio.Future` which gets done whenever
    response arrives or error occurs.

    Parameters
    ----------
    snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine`
        Class instance representing SNMP engine.

    authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
        Class instance representing SNMP credentials.

    transportTarget : :py:class:`~pysnmp.hlapi.asyncio.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncio.Udp6TransportTarget`
        Class instance representing transport type along with SNMP peer address.

    contextData : :py:class:`~pysnmp.hlapi.ContextData`
        Class instance representing SNMP ContextEngineId and ContextName values.

    \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
        One or more class instances representing MIB variables to place
        into SNMP request.

    Other Parameters
    ----------------
    \*\*options :
        Request options:

            * `lookupMib` - load MIB and resolve response MIB variables at
              the cost of slightly reduced performance. Default is `True`.

    Yields
    ------
    errorIndication : str
        True value indicates SNMP engine error.
    errorStatus : str
        True value indicates SNMP PDU error.
    errorIndex : int
        Non-zero value refers to `varBinds[errorIndex-1]`
    varBinds : tuple
        A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
        instances representing MIB variables returned in SNMP response.

    Raises
    ------
    PySnmpError
        Or its derivative indicating that an error occurred while
        performing SNMP operation.

    Examples
    --------
    >>> import asyncio
    >>> from pysnmp.hlapi.asyncio import *
    >>>
    >>> @asyncio.coroutine
    ... def run():
    ...     errorIndication, errorStatus, errorIndex, varBinds = yield from setCmd(
    ...         SnmpEngine(),
    ...         CommunityData('public'),
    ...         UdpTransportTarget(('demo.snmplabs.com', 161)),
    ...         ContextData(),
    ...         ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386')
    ...     )
    ...     print(errorIndication, errorStatus, errorIndex, varBinds)
    >>>
    >>> asyncio.get_event_loop().run_until_complete(run())
    (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('Linux i386'))])
    >>>

    """

    def __cbFun(snmpEngine, sendRequestHandle,
                errorIndication, errorStatus, errorIndex,
                varBinds, cbCtx):
        lookupMib, future = cbCtx
        if future.cancelled():
            return
        try:
            varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine, varBinds,
                                                        lookupMib)
        except Exception as e:
            future.set_exception(e)
        else:
            future.set_result(
                (errorIndication, errorStatus, errorIndex, varBindsUnmade)
            )

    addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget)

    future = asyncio.Future()

    cmdgen.SetCommandGenerator().sendVarBinds(
        snmpEngine, addrName, contextData.contextEngineId,
        contextData.contextName,
        vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun,
        (options.get('lookupMib', True), future)
    )
    return future
コード例 #27
0
ファイル: setgen.py プロジェクト: ithek/pysnmp
#    snmpEngine, 'my-router',
#    unix.domainName, '/tmp/snmp-agent',
#    'my-creds'
#)


# Error/response reciever
def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBinds, cbCtx):
    if errorIndication:
        print(errorIndication)
    elif errorStatus and errorIndex:
        print('%s at %s' %
              (errorStatus.prettyPrint(), varBinds[int(errorIndex) - 1]))
    elif errorStatus:
        print(errorStatus.prettyPrint())
    else:
        for oid, val in varBinds:
            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))


# Prepare request to be sent
cmdgen.SetCommandGenerator().sendReq(
    snmpEngine, 'my-router',
    (((1, 3, 6, 1, 2, 1, 1, 1, 0), rfc1902.OctetString('Grinch')),
     ((1, 3, 6, 1, 2, 1, 1, 2, 0), rfc1902.ObjectName('1.3.6.1.4.1.20408.4'))),
    cbFun)

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