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


Python config.addContext函数代码示例

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


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

示例1: cfgNtfOrg

 def cfgNtfOrg(self, authData, transportTarget, notifyType, tagList):
     addrName, paramsName = self.cfgCmdGen(
         authData, transportTarget, tagList
         )
     k = paramsName, tagList, notifyType
     if self.__knownNotifyNames.has_key(k):
         notifyName, _ = self.__knownNotifyNames[k]
     else:
         notifyName = 'n%s' % cmdgen.nextID()
         config.addNotificationTarget(
             self.snmpEngine,
             notifyName,
             paramsName,
             tagList,
             notifyType
             )
         self.__knownNotifyNames[k] = notifyName, paramsName
     if not self.__knownAuths.has_key(authData):
         subTree = (1,3,6)
         config.addTrapUser(
             self.snmpEngine,
             authData.securityModel,
             authData.securityName,
             authData.securityLevel,
             subTree
             )
         self.__knownAuths[authData] = subTree
     if self.snmpContext is None:
         self.snmpContext = context.SnmpContext(self.snmpEngine)
         config.addContext(
             self.snmpEngine, ''  # this is leaky
         )
     return notifyName
开发者ID:chrisliom,项目名称:pysnmp,代码行数:33,代码来源:ntforg.py

示例2: __init__

    def __init__(self, udpIp, udpPort):
        # Create SNMP engine with autogenernated engineID and pre-bound
        # to socket transport dispatcher
        self.snmpEngine = engine.SnmpEngine()
        self.mibBuilder = self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

        mibPath = self.mibBuilder.getMibPath() + ('.',)
        self.mibBuilder.setMibPath(*mibPath)

        # Setup UDP over IPv4 transport endpoint
        config.addSocketTransport(
            self.snmpEngine,
            udp.domainName,
            udp.UdpSocketTransport().openServerMode((udpIp, udpPort))
        )

        print 'Publishing readings via SNMP'
        print 'Agent address {}:{}'.format(udpIp, udpPort)
        print 'Community name public'

        # v1/2 setup
        config.addV1System(self.snmpEngine, 'test-agent', 'public')

        # v3 setup
        config.addV3User(
            self.snmpEngine, 'test-user'
        )

        # VACM setup
        config.addContext(self.snmpEngine, '')
        config.addRwUser(self.snmpEngine, 1, 'test-agent', 'noAuthNoPriv', (1,3,6)) # v1
        config.addRwUser(self.snmpEngine, 2, 'test-agent', 'noAuthNoPriv', (1,3,6)) # v2c
        config.addRwUser(self.snmpEngine, 3, 'test-user', 'noAuthNoPriv', (1,3,6)) # v3

        # SNMP context
        snmpContext = context.SnmpContext(self.snmpEngine)

        # Apps registration
        cmdrsp.GetCommandResponder(self.snmpEngine, snmpContext)
        cmdrsp.SetCommandResponder(self.snmpEngine, snmpContext)
        cmdrsp.NextCommandResponder(self.snmpEngine, snmpContext)
        cmdrsp.BulkCommandResponder(self.snmpEngine, snmpContext)

        MibScalarInstance, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance')

        class ScalarFromCallback(MibScalarInstance):
            def __init__(self, sensorId, valueGetter, typeName, instId, syntax):
                MibScalarInstance.__init__(self, typeName, instId, syntax)
                self.valueGetter = valueGetter

            def readTest(self, name, val, idx, (acFun, acCtx)):
                if not self.valueGetter():
                    raise error.NoAccessError(idx=idx, name=name)

            def readGet(self, name, val, idx, (acFun, acCtx)):
                value = self.valueGetter()
                if not value:
                    raise error.NoAccessError(idx=idx, name=name)
                else:
                    return name, self.syntax.clone(value)
开发者ID:InviNets,项目名称:ReadingsToSNMP,代码行数:60,代码来源:publish_sensor_readings.py

示例3: __init__

    def __init__(self, snmpEngine=None, snmpContext=None):
        if snmpEngine is None:
            self.snmpEngine = snmpEngine = SnmpEngine()
        else:
            self.snmpEngine = snmpEngine

        if snmpContext is None:
            self.snmpContext = context.SnmpContext(self.snmpEngine)
            config.addContext(
                self.snmpEngine, ''  # this is leaky
            )
        else:
            self.snmpContext = snmpContext

        self.mibViewController = self.vbProcessor.getMibViewController(self.snmpEngine)
开发者ID:437049211,项目名称:PyQYT,代码行数:15,代码来源:ntforg.py

示例4: __init__

    def __init__(self, snmpEngine=None, snmpContext=None):
        cmdgen.AsynCommandGenerator.__init__(self, snmpEngine)
        self.__asyncNtfOrg = AsyncNotificationOriginator()

        # grab/create MibViewController from/for the real AsyncCommandGen
        cache = self.__asyncNtfOrg._getCmdCache(self.snmpEngine)
        self.mibViewController = cache['mibViewController']

        if snmpContext is None:
            self.snmpContext = context.SnmpContext(self.snmpEngine)
            config.addContext(
                self.snmpEngine, ''  # this is leaky
            )
        else:
            self.snmpContext = snmpContext
开发者ID:InviNets,项目名称:ReadingsToSNMP,代码行数:15,代码来源:ntforg.py

示例5: initTarget

def initTarget(host='127.0.0.1', port=162, community='LIC_OSS'):
    #global snmpEngine, snmpContext, ntfOrg
    # Create SNMP engine instance
    snmpEngine = engine.SnmpEngine()
    
    # SecurityName <-> CommunityName mapping
    config.addV1System(snmpEngine, 'my-area', community)
    
    # Specify security settings per SecurityName (SNMPv2c -> 1)
    config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
    
    # Setup transport endpoint and bind it with security settings yielding
    # a target name
    config.addSocketTransport(
        snmpEngine,
        udp.domainName,
        udp.UdpSocketTransport().openClientMode()
    )
    config.addTargetAddr(
        snmpEngine, 'my-nms',
        udp.domainName, (host, port),
        'my-creds',
        tagList='all-my-managers'
    )
    
    # Specify what kind of notification should be sent (TRAP or INFORM),
    # 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 default SNMP context where contextEngineId == SnmpEngineId
    snmpContext = context.SnmpContext(snmpEngine)
    
    # Create Notification Originator App instance. 
    ntfOrg = ntforg.NotificationOriginator(snmpContext)
    return snmpEngine, ntfOrg
开发者ID:lowitty,项目名称:alarmfiles,代码行数:45,代码来源:SnmpTraps.py

示例6: cfgNtfOrg

 def cfgNtfOrg(self, authData, transportTarget, notifyType):
     addrName, paramsName = self.cfgCmdGen(authData, transportTarget)
     tagList = transportTarget.tagList.split()
     if not tagList:
         tagList = ['']
     for tag in tagList:
         notifyNameKey = paramsName, tag, notifyType
         if notifyNameKey in self.__knownNotifyNames:
             notifyName, paramsName, useCount = self.__knownNotifyNames[notifyNameKey]
             self.__knownNotifyNames[notifyNameKey] = notifyName, paramsName, useCount + 1
         else:
             notifyName = 'n%s' % nextID()
             config.addNotificationTarget(
                 self.snmpEngine,
                 notifyName,
                 paramsName,
                 tag,
                 notifyType
             )
             self.__knownNotifyNames[notifyNameKey] = notifyName, paramsName, 1
     authDataKey = authData.securityName, authData.securityModel
     if  authDataKey in self.__knownAuths:
         authDataX, subTree, useCount = self.__knownAuths[authDataKey]
         self.__knownAuths[authDataKey] = authDataX, subTree, useCount + 1
     else:
         subTree = (1,3,6)
         config.addTrapUser(
             self.snmpEngine,
             authData.securityModel,
             authData.securityName,
             authData.securityLevel,
             subTree
         )
         self.__knownAuths[authDataKey] = authData, subTree, 1
     if self.snmpContext is None:
         self.snmpContext = context.SnmpContext(self.snmpEngine)
         config.addContext(
             self.snmpEngine, ''  # this is leaky
         )
     return notifyName
开发者ID:BoundaryDev,项目名称:boundary-plugin-mongodb-enterprise-dev,代码行数:40,代码来源:ntforg.py

示例7: sent

    snmpEngine, 'my-nms',
    udp.domainName, ('104.236.166.95', 162),
    'my-creds',
    tagList='all-my-managers'
)

# Specify what kind of notification should be sent (TRAP or INFORM),
# 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', 'inform'
)

# Allow NOTIFY access to Agent's MIB by this SNMP model (3), securityLevel
# and SecurityName
config.addContext(snmpEngine, '')
config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (), (), (1, 3, 6))

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

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


# Error/confirmation receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(snmpEngine, sendRequestHandle, errorIndication,
          errorStatus, errorIndex, varBinds, cbCtx):
    print('Notification %s, status - %s' % (
        sendRequestHandle, errorIndication and errorIndication or 'delivered'
    )
开发者ID:rbreesems,项目名称:pysnmp,代码行数:31,代码来源:usm-md5-none.py

示例8: start

	def start(self):
		if self._engine is None:
			# Create SNMP engine with autogenernated engineID and pre-bound
			# to socket transport dispatcher
			self._engine = engine.SnmpEngine()
			
			# Setup UDP over IPv4 transport endpoint
		try:
			iface = ('0.0.0.0', self.port)
			self._logger.info("[pid: %d] Starting SNMP server on %s:%d",  os.getpid(), iface[0], iface[1])
			config.addSocketTransport(
			self._engine,
			udp.domainName,
			udp.UdpSocketTransport().openServerMode(iface)
			)
		except CarrierError:
			self._logger.error('Can\'t run SNMP agent on port %d: Address already in use', self.port)
			raise
		
		mibBuilder = self._engine.msgAndPduDsp.mibInstrumController.mibBuilder
			
		MibSources = mibBuilder.getMibPath()
		sources =  ['/mibs','/mibs/instances']
		for source in sources:
			MibSources += ((os.path.realpath(os.path.dirname(__file__) + source), ))
		apply(mibBuilder.setMibPath, MibSources)
			
		try:
			mibBuilder.loadModules(*self._modules)
		except SmiError:
			self._logger.warn('Can\'t load modules')
			raise

		config.addV1System(self._engine, self._security_name, self._community_name)
			
		# VACM setup
		config.addContext(self._engine, '')
		config.addRwUser(self._engine, 1, self._security_name, 'noAuthNoPriv', (1,3,6)) # v1
		config.addRwUser(self._engine, 2, self._security_name, 'noAuthNoPriv', (1,3,6)) # v2c
			
		# SNMP context
		snmpContext = context.SnmpContext(self._engine)
		# Apps registration
		cmdrsp.GetCommandResponder(self._engine, snmpContext)
		cmdrsp.SetCommandResponder(self._engine, snmpContext)
		cmdrsp.NextCommandResponder(self._engine, snmpContext)
		cmdrsp.BulkCommandResponder(self._engine, snmpContext)
			
		# Start server
		self._logger.debug('Starting transport dispatcher')
		self._engine.transportDispatcher.jobStarted(1)
		try:
			self._logger.debug('Run transport dispatcher')
			self._engine.transportDispatcher.runDispatcher()
		except select.error, e:
			if e.args[0] == 9: 
				# 'Bad file descriptor'
				# Throws when dispatcher closed from another thread
				pass
			else:
				raise
开发者ID:golovast,项目名称:scalarizr,代码行数:61,代码来源:agent.py

示例9: __init__

  def __init__(self, mibPath, temperatureValue, snmpRelays, criticalStatus=True):
    from types import ListType, TupleType,StringTypes
    from re import compile,search
    from socket import gethostbyname

    extractPaths=compile(r'[,:]')
    checkIP=compile(r'(\d{1,3}\.){3}\d{1,3}')

    # Create SNMP engine instance
    self.snmpEngine = engine.SnmpEngine()

    if not temperatureValue:
      raise ValueError, 'A temperature must be provided'
    
    self.temperature=temperatureValue
    #print "============>mibPath type: %s" %type(mibPath)
    if type(mibPath) in StringTypes:
      mibPathTuple=tuple(extractPaths.split(mibPath))
    elif type(mibPath) in (ListType, TupleType):
      mibPathTuple=tuple(mibPath)
    else:
      mibPathTuple=('/usr/local/share/snmp/python/',)

    mibBuilder = self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

    #print mibPathTuple
    mibSources = mibBuilder.getMibPath() + mibPathTuple
    mibBuilder.setMibPath(*mibSources)

    mibBuilder.loadModules( 'USC-IGFAE-MIB' )

    if type(snmpRelays) in StringTypes:
      snmpRelays=snmpRelays.split(',')
    elif not type(snmpRelays) in (ListType,TupleType):
      raise TypeError, 'The list of SNMP relays must be a string or a list or tuple of strings'
    
    
    (temperatureCritical, temperatureOK, self.roomTemp) = mibBuilder.importSymbols('USC-IGFAE-MIB','temperatureCritical', 'temperatureOK', 'roomTemp' )

    # SecurityName <-> CommunityName mapping
    config.addV1System(self.snmpEngine, 'Arduino', 'ups')

    # Specify security settings per SecurityName (SNMPv2c -> 1)
    config.addTargetParams(self.snmpEngine, 'creds', 'Arduino', 'noAuthNoPriv', 0)

    # Setup transport endpoint and bind it with security settings yielding
    # a target name
    config.addSocketTransport(
      self.snmpEngine,
      udp.domainName,
      udp.UdpSocketTransport().openClientMode()
    )

    index=0
    for machine in snmpRelays:
      index=index+1
      if not checkIP.match(machine):
        try:
          machine=gethostbyname(machine)
        except:
          continue

      #print "==============>SNMP relay  IP: %s" % machine
      config.addTargetAddr(
        self.snmpEngine, 'NMS%s' % index,
        udp.domainName, (machine, 162),
        'creds',
        tagList='managers'
      )

    # Specify what kind of notification should be sent (TRAP or INFORM),
    # to what targets (chosen by tag) and what filter should apply to
    # the set of targets (selected by tag)
    config.addNotificationTarget(
      self.snmpEngine, 'sendShutdownTrap', 'my-filter', 'managers', 'trap'
    )

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

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

    # Create default SNMP context where contextEngineId == SnmpEngineId
    snmpContext = context.SnmpContext(self.snmpEngine)

    if criticalStatus:
      self.trap=temperatureCritical
    else:
      self.trap=temperatureOK
      
    # Create Notification Originator App instance.
    ntforg.NotificationOriginator.__init__(self,snmpContext)
开发者ID:vfalbor,项目名称:nagios-arduino,代码行数:95,代码来源:Send_Trap.py

示例10: sent

# Second target
config.addTargetAddr(
    snmpEngine, "my-nms-2", udp.domainName, ("195.218.195.228", 162), "my-creds", tagList="all-my-managers"
)
# Third target
config.addTargetAddr(
    snmpEngine, "my-nms-3", udp.domainName, ("195.218.195.228", 162), "my-creds", tagList="all-my-managers"
)

# Specify what kind of notification should be sent (TRAP or INFORM)
# to what targets (chosen by tag) and with what credentials.
config.addNotificationTarget(snmpEngine, "my-notification", "my-creds", "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,
    # Notification targets
    "my-notification",  # notification targets
    None,
    "",  # contextEngineId, contextName
    # var-binds
开发者ID:crazy-canux,项目名称:pysnmp,代码行数:31,代码来源:send-trap-to-multiple-managers.py


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