def __init__(self, controller, cfg): threading.Thread.__init__(self) self.controller = controller self.cfg = cfg self.snmp_engine = engine.SnmpEngine() self.count = 0 # Transport setup ipv4 = True if IPAddress(self.cfg.snmp.snmp_ip).version == 6: ipv4 = False # Transport setup if ipv4: # UDP over IPv4, first listening interface/port config.addSocketTransport( self.snmp_engine, udp.domainName + (1, ), udp.UdpTransport().openServerMode( (self.cfg.snmp.snmp_ip, self.cfg.snmp.snmp_port))) else: # UDP over IPv6, first listening interface/port config.addSocketTransport( self.snmp_engine, udp6.domainName + (1, ), udp6.Udp6Transport().openServerMode( (self.cfg.snmp.snmp_ip, self.cfg.snmp.snmp_port))) # SecurityName <-> CommunityName mapping config.addV1System(self.snmp_engine, self.cfg.snmp.snmp_sec_area, self.cfg.snmp.snmp_comm_str) ntfrcv.NotificationReceiver(self.snmp_engine, self.cb_fun)
def traprcv(self): """Create SNMP engine with autogenernated engineID and pre-bound to socket transport dispatcher""" snmpEngine = engine.SnmpEngine() """Transport setup # UDP over IPv4, first listening interface/port""" config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode((self.hosta, self.porta)) ) """UDP over IPv4, second listening interface/port""" config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openServerMode((self.hostb, self.portb)) ) """SNMPv1/2c setup # SecurityName <-> CommunityName mapping""" config.addV1System(snmpEngine, 'my-area', 'public') """Register SNMP Application at the SNMP engine""" ntfrcv.NotificationReceiver(snmpEngine, self.cbFun) """this job would never finish""" snmpEngine.transportDispatcher.jobStarted(1) """Run I/O dispatcher which would receive queries and send confirmations""" try: snmpEngine.transportDispatcher.runDispatcher() except IOError: snmpEngine.transportDispatcher.closeDispatcher() raise finally: pass
def initialize_snmp_listener(community, port): # Bind SNMP to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4, first listening interface/port config.addTransport(snmpEngine, udp.domainName + (1, ), udp.UdpTransport().openServerMode(('0.0.0.0', port))) logger.debug(f'listening on port: {port} - the standard port is 162') # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', community) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, handle_mac_notification) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: logger.debug(f"SNMP Engine running") snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() logger.debug(f"SNMP Engine failure ") raise
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)
def receiveTraps(): #checks for incoming traps try: snmpEngine = SnmpEngine() TrapAgentAddress = 'localhost' Port = 162 print("Now listening for Trap on " + TrapAgentAddress + ":" + str(Port) + "...\n") config.addTransport( snmpEngine, udp.domainName + (1, ), udp.UdpTransport().openServerMode((TrapAgentAddress, Port))) config.addV1System(snmpEngine, 'community', 'public') def trapOutput(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print("Received new Trap message") for name, val in varBinds: #iterates through each received oid pair print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) #pretty Print to make it readable return ntfrcv.NotificationReceiver(snmpEngine, trapOutput) snmpEngine.transportDispatcher.jobStarted(1) try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise except KeyboardInterrupt: return
def setCommunity(snmpEngine, security, community, version='2c', tag=''): """Configure SNMP v1/v2c community name and VACM access. Args: snmpEngine (object): pysnmp `SnmpEngine` class instance security (str): SNMP security name. Used in SNMP engine configuration primarily as an ID for the given SNMP v1/v2c authentication information community (str): SNMP v1/v2c community name version (str): SNMP version to use for this configuration entry. Either 'v1' or 'v2c'. tag (str): Tags this SNMP configuration entry. Tags can be used internally by SNMP engine for looking up desired SNMP authentication information. Returns: str: effective SNMP authentication and privacy level ('noAuthNoPriv') """ mpModel = MP_MODELS[version] authLevel = 'noAuthNoPriv' config.addV1System( snmpEngine, security, communityName=community, transportTag=tag) config.addVacmUser( snmpEngine, mpModel, security, authLevel, (1, 3, 6), (1, 3, 6), (1, 3, 6)) return authLevel
def listen( address=DEFAULT_ADDRESSS, port=DEFAULT_PORT, community=DEFAULT_COMMUNITY, mibs=DEFAULT_MIBS, ): """Listen to and SNMP trap and print events.""" # Based on pySNMP example code. mib_builder = builder.MibBuilder() compiler.addMibCompiler(mib_builder) mib_builder.loadModules(*mibs) global _view_controller _view_controller = view.MibViewController(mib_builder) loop = asyncio.get_event_loop() snmp_engine = engine.SnmpEngine() print(f"Agent is listening SNMP Trap on {address}, Port: {port}") if port < 1024: print( "WARNING: Port < 1024. Root priviledges or authbind required on *nix systems." ) print("-" * 79) config.addTransport( snmp_engine, udp.domainName + (1, ), udp.UdpTransport().openServerMode((address, port)), ) config.addV1System(snmp_engine, community, community) ntfrcv.NotificationReceiver(snmp_engine, _listen_callback) print("Press CTRL-C to quit.") loop.run_forever()
def run(self): """ Main Transport Dispatcher Loop """ # Create SNMP engine with auto generated engineID and pre-bound # to socket transport dispatcher self.snmp_engine = engine.SnmpEngine() # Transport setup ip_address, net_mask = get_net_addresses() # UDP over IPv4, first listening interface/port config.addSocketTransport( self.snmp_engine, udp.domainName + (1, ), udp.UdpTransport().openServerMode((ip_address, SNMP_TRAP_PORT))) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV1System(self.snmp_engine, 'my-area', SNMP_TRAP_COMMUNITY) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(self.snmp_engine, self.callback_function) # this job would never finish self.snmp_engine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send confirmations try: self.snmp_engine.transportDispatcher.runDispatcher() except: self.snmp_engine.transportDispatcher.closeDispatcher() raise
def _setup(self, agent, context, host, port): # TODO support changes to context etc and make a new connection??? if self.snmpEngine is None: self.snmpEngine = engine.SnmpEngine() else: return # already setup if isinstance(agent, UsmUserData): config.addV3User(self.snmpEngine, agent.securityName, agent.authProtocol, agent.authKey, agent.privProtocol, agent.privKey) config.addTargetParams(self.snmpEngine, 'myParams', agent.securityName, agent.securityLevel) else: config.addV1System(self.snmpEngine, agent, context) config.addTargetParams(self.snmpEngine, 'myParams', agent, 'noAuthNoPriv', 1) config.addTargetAddr(self.snmpEngine, 'myRouter', config.snmpUDPDomain, (host, port), 'myParams', timeout=900) config.addSocketTransport(self.snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode())
def run(self) -> None: self.snmpEngine = engine.SnmpEngine() config.addSocketTransport( self.snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 1161)) ) config.addV1System(self.snmpEngine, 'my-area', 'public', contextName='my-context') config.addVacmUser(self.snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6), (1, 3, 6)) snmpContext = context.SnmpContext(self.snmpEngine) class SimpleController(instrum.AbstractMibInstrumController): def readVars(self, varBinds, acInfo=(None, None)): return [(ov[0], v2c.Integer(random.uniform(120, 140))) for ov in varBinds] snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name SimpleController() # Management Instrumentation ) cmdrsp.GetCommandResponder(self.snmpEngine, snmpContext) # cmdrsp.SetCommandResponder(self.snmpEngine, snmpContext) self.snmpEngine.transportDispatcher.jobStarted(1) try: self.snmpEngine.transportDispatcher.runDispatcher() except: self.snmpEngine.transportDispatcher.closeDispatcher() raise
def init_snmp_engine(self): # each SNMP-based application has an engine self._snmpEngine = engine.SnmpEngine() # config.addTransport(self._snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()) config.addSocketTransport(self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('', self.port))) # SecurityName <-> CommunityName mapping. # config.addV1System(self._snmpEngine, 'my-area', 'public') # Allow read MIB access for this user / securityModels at VACM # config.addVacmUser(self._snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6)) # ===== SNMP v2c ===== # SecurityName <-> CommunityName mapping config.addV1System(self._snmpEngine, "public-v1-sec", "public") config.addVacmUser(self._snmpEngine, 2, 'public-v1-sec', 'noAuthNoPriv', (1, 3, 6)) # ===== SNMP v3 support ===== config.addV3User(self._snmpEngine, 'user1', config.usmHMACMD5AuthProtocol, 'authkey1') config.addVacmUser(self._snmpEngine, 3, 'user1', 'authNoPriv', (1, 3, 6)) # each app has one or more contexts self._snmpContext = context.SnmpContext(self._snmpEngine)
def _snmp_v2v3_config(self): """Configures snmp v2 and v3 user parameters.""" community_str = constants.SNMP_COMMUNITY_STR config.addV1System(self.snmp_engine, community_str, community_str) auth_priv_protocols = { 'usmHMACMD5AuthProtocol': config.usmHMACMD5AuthProtocol, 'usmHMACSHAAuthProtocol': config.usmHMACSHAAuthProtocol, 'usmAesCfb128Protocol': config.usmAesCfb128Protocol, 'usmAesCfb256Protocol': config.usmAesCfb256Protocol, 'usmAesCfb192Protocol': config.usmAesCfb192Protocol, 'usmDESPrivProtocol': config.usmDESPrivProtocol, 'usmNoAuthProtocol': config.usmNoAuthProtocol, 'usmNoPrivProtocol': config.usmNoPrivProtocol } config.addV3User(self.snmp_engine, userName=constants.SNMP_USM_USER, authKey=constants.SNMP_V3_AUTHKEY, privKey=constants.SNMP_V3_PRIVKEY, authProtocol=auth_priv_protocols.get( constants.SNMP_V3_AUTH_PROTOCOL, config.usmNoAuthProtocol), privProtocol=auth_priv_protocols.get( constants.SNMP_V3_PRIV_PROTOCOL, config.usmNoPrivProtocol), securityEngineId=v2c.OctetString( hexValue=constants.SNMP_ENGINE_ID)) return
def _setup(self): """ Setup Server """ assert isinstance(self._callbacks, list), \ "callbacks should be list of functions type not %s" % type( self._callbacks) snmp_engine = engine.SnmpEngine() build = snmp_engine.getMibBuilder() if self._add_mib_dir: if not os.path.exists(self._add_mib_dir): raise PiatError("mib dir does not exist, dir=%r" % self._add_mib_dir) if not os.path.isdir(self._add_mib_dir): raise PiatError( "add_mib_dir should be a directory not a file, add_mib_dir=%r" % self._add_mib_dir) build.addMibSources(builder.DirMibSource(self._add_mib_dir)) build.loadModules() viewer = view.MibViewController(build) # UDP over IPv4, first listening interface/port transport = udp.UdpTransport() config.addTransport(snmp_engine, udp.domainName + (1, ), transport.openServerMode(('0.0.0.0', self._port))) # SecurityName <-> CommunityName mapping config.addV1System(snmp_engine, '????', self._community) # Register SNMP Application at the SNMP engine handler = TrapsHandler(self._callbacks, viewer) ntfrcv.NotificationReceiver(snmp_engine, handler.handle) self._snmpEngine = snmp_engine
def _add_snmp_config(self, ctxt, new_config): LOG.info("Add snmp config:%s" % new_config) storage_id = new_config.get("storage_id") version_int = self._get_snmp_version_int(ctxt, new_config.get("version")) if version_int == constants.SNMP_V2_INT or \ version_int == constants.SNMP_V1_INT: community_string = new_config.get("community_string") community_index = self._get_community_index(storage_id) config.addV1System(self.snmp_engine, community_index, community_string, contextName=community_string) else: username = new_config.get("username") engine_id = new_config.get("engine_id") auth_key = new_config.get("auth_key") auth_protocol = new_config.get("auth_protocol") privacy_key = new_config.get("privacy_key") privacy_protocol = new_config.get("privacy_protocol") if auth_key is not None: auth_key = cryptor.decode(auth_key) if privacy_key is not None: privacy_key = cryptor.decode(privacy_key) config.addV3User( self.snmp_engine, userName=username, authKey=auth_key, privKey=privacy_key, authProtocol=self._get_usm_auth_protocol(ctxt, auth_protocol), privProtocol=self._get_usm_priv_protocol(ctxt, privacy_protocol), securityEngineId=v2c.OctetString(hexValue=engine_id))
def __init__(self, mibObjects, sqlObject, _rootDir, server_options): """ mibObjects - a list of MibObject tuples that this agent will serve """ #each SNMP-based application has an engine self._snmpEngine = engine.SnmpEngine() #open a UDP socket to listen for snmp requests config.addSocketTransport(self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('', int(server_options['port'])))) #add a v2 user with the community string public config.addV1System(self._snmpEngine, "agent", server_options['community']) #let anyone accessing 'public' read anything in the subtree below, #which is the enterprises subtree that we defined our MIB to be in config.addVacmUser(self._snmpEngine, int(server_options['version']), "agent", "noAuthNoPriv", readSubTree=(1,3,6,1,4,1)) #each app has one or more contexts self._snmpContext = context.SnmpContext(self._snmpEngine) #the builder is used to load mibs. tell it to look in the #current directory for our new MIB. We'll also use it to #export our symbols later mibBuilder = self._snmpContext.getMibInstrum().getMibBuilder() mibSources = mibBuilder.getMibSources() + (builder.DirMibSource(os.path.join(_rootDir, 'lib_mib_py')),) mibBuilder.setMibSources(*mibSources) #our variables will subclass this since we only have scalar types #can't load this type directly, need to import it MibScalarInstance, = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') #export our custom mib for mibObject in mibObjects: nextVar, = mibBuilder.importSymbols(mibObject.mibName, mibObject.objectType) if mibObject.objMib.flag: #je suis une table for client in sqlObject.getClientsId(): instance = createVariable(MibScalarInstance, mibObject.objMib, mibObject.valueFunc, nextVar.name,(client['ClientId'],), nextVar.syntax) listName = list(nextVar.name) listName.append(client['ClientId'] ) newName = tuple(listName) instanceDict = {str(newName)+"Instance":instance} mibBuilder.exportSymbols(mibObject.mibName, **instanceDict) else : instance = createVariable(MibScalarInstance, mibObject.objMib, mibObject.valueFunc, nextVar.name,(0,), nextVar.syntax) #class ,class with fonc , nom de la fonction , oid , type d'oid #need to export as <var name>Instance instanceDict = {str(nextVar.name)+"Instance":instance} mibBuilder.exportSymbols(mibObject.mibName, **instanceDict) # tell pysnmp to respotd to get, getnext, and getbulk cmdrsp.GetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.NextCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.BulkCommandResponder(self._snmpEngine, self._snmpContext)
def __init__(self, mibObjects): """ mibObjects - a list of MibObject tuples that this agent will serve """ #each SNMP-based application has an engine self._snmpEngine = engine.SnmpEngine() #open a UDP socket on port 161 to listen for snmp requests config.addSocketTransport(self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('', 161))) #Here we configure two distinct Community Strings to control read and write #operations. public --> Read only, private --> Read/Write config.addV1System(self._snmpEngine, "agent", "public") config.addV1System(self._snmpEngine, 'my-write-area', 'private') #let anyone accessing 'public' read anything in the subtree below, #which is the enterprises subtree that we defined our MIB to be in config.addVacmUser(self._snmpEngine, 2, "agent", "noAuthNoPriv", readSubTree=(1,3,6,1,4,1)) #let anyone accessing 'private' read and write anything in the subtree below, #which is the enterprises subtree that we defined our MIB to be in config.addVacmUser(self._snmpEngine, 2, 'my-write-area', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 4, 1), writeSubTree=(1, 3, 6, 1, 4, 1)) #Create Agent context self._snmpContext = context.SnmpContext(self._snmpEngine) #the builder is used to load mibs. tell it to look in the #current directory for our new MIB. We'll also use it to #export our symbols later mibBuilder = self._snmpContext.getMibInstrum().getMibBuilder() mibSources = mibBuilder.getMibSources() + (builder.DirMibSource('.'),) mibBuilder.setMibSources(*mibSources) MibScalarInstance, = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') #export our custom mib for mibObject in mibObjects: nextVar, = mibBuilder.importSymbols(mibObject.mibName, mibObject.objectType) instance = createVariable(MibScalarInstance, mibObject.valueFunc, mibObject.valueSetFunc, nextVar.name, (0,), nextVar.syntax) #need to export as <var name>Instance instanceDict = {str(nextVar.name)+"Instance":instance} mibBuilder.exportSymbols(mibObject.mibName, **instanceDict) # tell pysnmp to respond to get, set, getnext, and getbulk cmdrsp.GetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.SetCommandResponder(self._snmpEngine,self._snmpContext) cmdrsp.NextCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.BulkCommandResponder(self._snmpEngine, self._snmpContext)
def test2(): from pysnmp.v4.proto.rfc1902 import ObjectName from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import cmdgen sysName = ObjectName("1.3.6.1.2.1.1.5.0") ip = "192.168.1.9" snmp_engine = engine.SnmpEngine() config.addV1System(snmp_engine, 'test-agent', "public") config.addTargetParams(snmp_engine, 'myParams', 'test-agent', 'noAuthNoPriv', 0) config.addTargetAddr( snmp_engine, 'myRouter', config.snmpUDPDomain, (ip, 161), 'myParams' ) config.addSocketTransport( snmp_engine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) cb = {} def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBinds'] = varBinds cmdgen.GetCommandGenerator().sendReq(snmp_engine, 'myRouter', ((sysName, None),), cbFun, cb) lastmemusage = 0 lastrefs = None errors = 0 while (errors < 2): snmp_engine.transportDispatcher.runDispatcher() print cb['varBinds'][0][1] snmp_engine.transportDispatcher.closeDispatcher() #asynCommandGenerator.flushConfig() newmemusage = resource.getrusage(resource.RUSAGE_SELF)[2] memdiff = (newmemusage - lastmemusage) newrefs = get_refcounts() if memdiff > 0: print "Leaked %d Kb... printing refcount diff" % memdiff if lastrefs == None: print "No previous refcount, skipping" else: print_ref_diffs(lastrefs, newrefs) errors = errors + 1 gc.collect() lastrefs = newrefs lastmemusage = newmemusage #print resource.getrusage(resource.RUSAGE_SELF)[3] time.sleep(1)
def _configureUsers(self, snmpEngine, snmpContext, params): logger.debug ( 'Configure users' ); for user in params.users: logger.debug ( 'Creating user "%s"', user.name ); # Compute a fake context name contextName = "%sSystem-context-%s" % (self.version,user.name) self.contexts[user.name] = contextName; # Register the community config.addV1System(snmpEngine=snmpEngine, securityName=contextName, communityName=user.name, contextName=contextName)
def addV1System(self, securityName, communityName, contextEngineId=None, contextName=None, transportTag=None): config.addV1System(self.snmpEngine, securityName, communityName, contextEngineId, contextName, transportTag) return
def configure_engine(engine, host='127.0.0.1', port=162): # UDP over IPv4, first listening interface/port config.addTransport( engine, udp.domainName + (1,), udp.UdpTransport().openServerMode((host, port)) ) config.addV1System(engine, 'my-area', 'public')
def cfgCmdGen(self, authData, transportTarget, tagList=''): if self.__knownAuths.has_key(authData): paramsName = self.__knownAuths[authData] else: paramsName = 'p%s' % nextID() if isinstance(authData, CommunityData): config.addV1System( self.snmpEngine, authData.securityName, authData.communityName ) config.addTargetParams( self.snmpEngine, paramsName, authData.securityName, authData.securityLevel, authData.mpModel ) elif isinstance(authData, UsmUserData): config.addV3User( self.snmpEngine, authData.securityName, authData.authProtocol, authData.authKey, authData.privProtocol, authData.privKey ) config.addTargetParams( self.snmpEngine, paramsName, authData.securityName, authData.securityLevel ) else: raise error.PySnmpError('Unsupported SNMP version') self.__knownAuths[authData] = paramsName if not self.__knownTransports.has_key(transportTarget.transportDomain): transport = transportTarget.openClientMode() config.addSocketTransport( self.snmpEngine, transportTarget.transportDomain, transport ) self.__knownTransports[transportTarget.transportDomain] = transport k = transportTarget, tagList if self.__knownTransportAddrs.has_key(k): addrName = self.__knownTransportAddrs[k] else: addrName = 'a%s' % nextID() config.addTargetAddr( self.snmpEngine, addrName, transportTarget.transportDomain, transportTarget.transportAddr, paramsName, transportTarget.timeout * 100, transportTarget.retries, tagList ) self.__knownTransportAddrs[k] = addrName return addrName, paramsName
def __init__(self, host, port, log_queue): self.log_queue = log_queue # Create SNMP engine self.snmpEngine = engine.SnmpEngine() # Transport setup udp_sock = gevent.socket.socket(gevent.socket.AF_INET, gevent.socket.SOCK_DGRAM) udp_sock.setsockopt(gevent.socket.SOL_SOCKET, gevent.socket.SO_BROADCAST, 1) udp_sock.bind((host, port)) # UDP over IPv4 self.addSocketTransport( self.snmpEngine, udp.domainName, udp_sock ) #SNMPv1 config.addV1System(self.snmpEngine, 'public-read', 'public') # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( self.snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( self.snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtocol, 'authkey1' ) # user: usr-sha-aes128, auth: SHA, priv AES/128 config.addV3User( self.snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(self.snmpEngine, 1, 'public-read', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-sha-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(self.snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(self.snmpEngine, snmpContext) cmdrsp.SetCommandResponder(self.snmpEngine, snmpContext) cmdrsp.NextCommandResponder(self.snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(self.snmpEngine, snmpContext)
def __init__(self, host, port, users, naming_scheme): """ host = public ip to listen on port = port to listen on (usually 161) users = list of ('username', 'password', 'privatekey', 'authPriv') #authentication method for snmp v3 if users is None, authentication will be snmp v1 public community string, read only """ self.naming_scheme = naming_scheme self.run = True self.users = users # Create SNMP engine self.snmpEngine = engine.SnmpEngine() # Get default SNMP context this SNMP engine serves self.snmpContext = context.SnmpContext(self.snmpEngine) # MIB builder self.mibBuilder = self.snmpContext.getMibInstrum().getMibBuilder() self.MibScalar, self.MibScalarInstance = self.mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalar', 'MibScalarInstance') # Transport setup # UDP over IPv4 try: config.addSocketTransport( self.snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((host, port))) print('Serving on port %s' % port) except error.CarrierError as carrier_error: if "[Errno 98]" in carrier_error.message: raise RuntimeError('Port %s is in use' % port) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES if users: for user in users: self._add_v3_md5_des_user(user) # Allow full MIB access for each user at VACM else: # SNMPv1 public community string setup config.addV1System(self.snmpEngine, 'my-read-area', 'public') self._add_user_permission( "1.3.6.1.2.1" ) #full walk permission, without this snmpwalk returns None # Overwrite default strings with custom name sysDescr, = self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMPv2-MIB', 'sysDescr') sysDescr = self.MibScalarInstance( sysDescr.name, (0, ), sysDescr.syntax.clone( "PySNMP engine - OVS 1.2.0 SNMP Agent")) # Get from config? self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.exportSymbols( 'SNMPv2-MIB', sysDescr) self._add_user_permission(self.naming_scheme.replace('.%s', ''))
def __init__(self, host, port, community): self.snmp = engine.SnmpEngine() self.snmp.registerTransportDispatcher(dispatch.TwistedDispatcher()) config.addV1System(self.snmp, 'my-area', community) config.addTargetParams(self.snmp, 'my-creds', 'my-area', 'noAuthNoPriv', 0) config.addSocketTransport(self.snmp, udp.domainName, udp.UdpTwistedTransport().openClientMode()) config.addTargetAddr(self.snmp, 'my-router', udp.domainName, (host, port), 'my-creds')
def __init__(self, host, port, rcommunity): self.snmpEngine = engine.SnmpEngine() config.addSocketTransport(self.snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((host, port))) config.addV1System(self.snmpEngine, 'my-area', rcommunity) config.addVacmUser(self.snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6)) self.snmpContext = context.SnmpContext(self.snmpEngine) self.mibBuilder = self.snmpContext.getMibInstrum().getMibBuilder() self.MibScalar, self.MibScalarInstance = self.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibScalarInstance') cmdrsp.GetCommandResponder(self.snmpEngine, self.snmpContext) cmdrsp.NextCommandResponder(self.snmpEngine, self.snmpContext) cmdrsp.BulkCommandResponder(self.snmpEngine, self.snmpContext)
def __init__(self, host, port, community): self.snmp = engine.SnmpEngine() self.snmp.registerTransportDispatcher(dispatch.TwistedDispatcher()) config.addV1System(self.snmp, 'my-area', community) config.addTargetParams(self.snmp, 'my-creds', 'my-area', 'noAuthNoPriv', 0) config.addSocketTransport(self.snmp, udp.domainName, udp.UdpTwistedTransport().openClientMode() ) config.addTargetAddr(self.snmp, 'my-router', udp.domainName, (host, port), 'my-creds')
def generator(cbCtx, ast): snmpEngine, ctx = cbCtx __SMGenerator().preorder(cbCtx, ast) # Commit collected data if ctx['versionId'] == 3: if 'securityName' not in ctx: raise error.PySnmpError('Security name not specified') if 'securityLevel' not in ctx: raise error.PySnmpError('Security level not specified') if ctx['securityLevel'] == 'noAuthNoPriv': if 'authKey' in ctx: del ctx['authKey'] if 'privKey' in ctx: del ctx['privKey'] elif ctx['securityLevel'] == 'authNoPriv': if 'privKey' in ctx: del ctx['privKey'] if 'authKey' in ctx: if 'authProtocol' not in ctx: ctx['authProtocol'] = config.usmHMACMD5AuthProtocol else: ctx['authProtocol'] = config.usmNoAuthProtocol ctx['authKey'] = None if 'privKey' in ctx: if 'privProtocol' not in ctx: ctx['privProtocol'] = config.usmDESPrivProtocol else: ctx['privProtocol'] = config.usmNoPrivProtocol ctx['privKey'] = None config.addV3User(snmpEngine, ctx['securityName'], ctx['authProtocol'], ctx['authKey'], ctx['privProtocol'], ctx['privKey']) # edit SNMP engine boots/uptime if 'engineBoots' in ctx: snmpEngineBoots, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( '__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots') snmpEngineBoots.setSyntax(snmpEngineBoots.getSyntax().clone( ctx['engineBoots'])) if 'engineTime' in ctx: snmpEngineTime, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( '__SNMP-FRAMEWORK-MIB', 'snmpEngineTime') snmpEngineTime.setSyntax(snmpEngineTime.getSyntax().clone( ctx['engineTime'])) else: # SNMPv1/v2c if 'communityName' not in ctx: raise error.PySnmpError('Community name not specified') ctx['securityName'] = 'my-agent' ctx['securityLevel'] = 'noAuthNoPriv' config.addV1System(snmpEngine, ctx['securityName'], ctx['communityName']) ctx['paramsName'] = ctx['securityName'] config.addTargetParams(snmpEngine, ctx['paramsName'], ctx['securityName'], ctx['securityLevel'], ctx['versionId'])
def __init__(self, mibObjects): """ mibObjects - a list of MibObject tuples that this agent will serve """ #each SNMP-based application has an engine self._snmpEngine = engine.SnmpEngine() #open a UDP socket to listen for snmp requests config.addSocketTransport(self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('', 161))) #add a v2 user with the community string public config.addV1System(self._snmpEngine, "agent", "public") #let anyone accessing 'public' read anything in the subtree below, #which is the enterprises subtree that we defined our MIB to be in config.addVacmUser(self._snmpEngine, 2, "agent", "noAuthNoPriv", readSubTree=(1, 3, 6, 1, 4, 1)) #each app has one or more contexts self._snmpContext = context.SnmpContext(self._snmpEngine) #the builder is used to load mibs. tell it to look in the #current directory for our new MIB. We'll also use it to #export our symbols later mibBuilder = self._snmpContext.getMibInstrum().getMibBuilder() mibSources = mibBuilder.getMibSources() + (builder.DirMibSource('.'), ) mibBuilder.setMibSources(*mibSources) mibBuilder.loadModules('HOST-RESOURCES-MIB') #our variables will subclass this since we only have scalar types #can't load this type directly, need to import it MibScalarInstance, = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') #export our custom mib for mibObject in mibObjects: nextVar, = mibBuilder.importSymbols(mibObject.mibName, mibObject.objectType) instance = createVariable(MibScalarInstance, mibObject.valueFunc, nextVar.name, (0, ), nextVar.syntax) #need to export as <var name>Instance instanceDict = {str(nextVar.name) + "Instance": instance} mibBuilder.exportSymbols(mibObject.mibName, **instanceDict) # tell pysnmp to respotd to get, getnext, and getbulk cmdrsp.GetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.NextCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.BulkCommandResponder(self._snmpEngine, self._snmpContext)
def main(): # Instantiate snmp engine snmpEngine = engine.SnmpEngine() # Load MIBs (for translation of the numeric OIDs) mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB') mibViewController = view.MibViewController(mibBuilder) # Transport setup # UDP over IPv6, listening interface/port config.addTransport( snmpEngine, udp6.domainName + (1,), udp6.Udp6Transport().openServerMode(('::', TRAP_PORT)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): # Translate numerical OIDs into human readable form varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds] # Turn on write permission for everyone os.umask(0) # Open file, append new data at the end with open(os.open(TRAP_LOG_PATH, os.O_CREAT | os.O_WRONLY, 0o777), 'a+') as f: t = time.gmtime() f.write('TRAP received on %s from ContextEngineId "%s", ContextName "%s" \n' % (time.strftime('%c', t), contextEngineId.prettyPrint(), contextName.prettyPrint())) # Write data in file for varbind in varBinds: f.write(varbind.prettyPrint()+'\n') f.write('\n') # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # Start a job that will never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise
def cfgCmdGen(self, authData, transportTarget): if authData not in self.__knownAuths: if isinstance(authData, CommunityData): config.addV1System(self.snmpEngine, authData.securityName, authData.communityName, authData.contextEngineId, authData.contextName, authData.tag) elif isinstance(authData, UsmUserData): config.addV3User(self.snmpEngine, authData.securityName, authData.authProtocol, authData.authKey, authData.privProtocol, authData.privKey, authData.contextEngineId) else: raise error.PySnmpError('Unsupported authentication object') self.__knownAuths[authData] = 1 k = authData.securityName, authData.securityLevel, authData.mpModel if k in self.__knownParams: paramsName = self.__knownParams[k] else: paramsName = 'p%s' % nextID() config.addTargetParams(self.snmpEngine, paramsName, authData.securityName, authData.securityLevel, authData.mpModel) self.__knownParams[k] = paramsName if transportTarget.transportDomain not in self.__knownTransports: transport = transportTarget.openClientMode() config.addSocketTransport(self.snmpEngine, transportTarget.transportDomain, transport) self.__knownTransports[transportTarget.transportDomain] = transport k = paramsName, transportTarget, transportTarget.tagList if k in self.__knownTransportAddrs: addrName = self.__knownTransportAddrs[k] else: addrName = 'a%s' % nextID() config.addTargetAddr(self.snmpEngine, addrName, transportTarget.transportDomain, transportTarget.transportAddr, paramsName, transportTarget.timeout * 100, transportTarget.retries, transportTarget.tagList) self.__knownTransportAddrs[k] = addrName return addrName, paramsName
def __init__(self, host, port, users, naming_scheme): """ host = public ip to listen on port = port to listen on (usually 161) users = list of ('username', 'password', 'privatekey', 'authPriv') #authentication method for snmp v3 if users is None, authentication will be snmp v1 public community string, read only """ self.naming_scheme = naming_scheme self.run = True self.users = users # Create SNMP engine self.snmpEngine = engine.SnmpEngine() # Get default SNMP context this SNMP engine serves self.snmpContext = context.SnmpContext(self.snmpEngine) # MIB builder self.mibBuilder = self.snmpContext.getMibInstrum().getMibBuilder() self.MibScalar, self.MibScalarInstance = self.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibScalarInstance') # Transport setup # UDP over IPv4 try: config.addSocketTransport(self.snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((host, port))) print('Serving on port %s' % port) except error.CarrierError as carrier_error : if "[Errno 98]" in carrier_error.message: raise RuntimeError('Port %s is in use' % port) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES if users: for user in users: self._add_v3_md5_des_user(user) # Allow full MIB access for each user at VACM else: # SNMPv1 public community string setup config.addV1System(self.snmpEngine, 'my-read-area', 'public') self._add_user_permission("1.3.6.1.2.1") #full walk permission, without this snmpwalk returns None # Overwrite default strings with custom name sysDescr, = self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-MIB', 'sysDescr') sysDescr = self.MibScalarInstance(sysDescr.name, (0,), sysDescr.syntax.clone("PySNMP engine - OVS 1.2.0 SNMP Agent")) # Get from config? self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.exportSymbols('SNMPv2-MIB', sysDescr) self._add_user_permission(self.naming_scheme.replace('.%s', ''))
def __init__(self, community, ip, version=1): self.__community = community self.__ip = ip self.__version = version self.__errorIndication = None self.__errorStatus = None self.__errorIndex = None self.__varBinds = None # self.__lock = threading.Lock() self.__snmp_engine = engine.SnmpEngine() config.addV1System(self.__snmp_engine, "test-agent", self.__community) config.addTargetParams(self.__snmp_engine, "myParams", "test-agent", "noAuthNoPriv", self.__version) config.addTargetAddr(self.__snmp_engine, "myRouter", config.snmpUDPDomain, (self.__ip, 161), "myParams") config.addSocketTransport(self.__snmp_engine, udp.domainName, udp.UdpSocketTransport().openClientMode())
def setTrapReceiver(self, host, community): config.addV1System(self._snmpEngine, 'nms-area', community) config.addVacmUser(self._snmpEngine, 2, 'nms-area', 'noAuthNoPriv', notifySubTree=(1, 3, 6, 1, 4, 1)) config.addTargetParams(self._snmpEngine, 'nms-creds', 'nms-area', 'noAuthNoPriv', 1) config.addTargetAddr(self._snmpEngine, 'my-nms', udp.domainName, (host, 162), 'nms-creds', tagList='all-my-managers') # set last parameter to 'notification' to have it send # informs rather than unacknowledged traps config.addNotificationTarget( self._snmpEngine, 'test-notification', 'my-filter', 'all-my-managers', 'trap')
def _add_snmp_config(self, ctxt, new_config): storage_id = new_config.get("storage_id") LOG.info("Start to add snmp trap config for storage: %s", storage_id) try: version_int = self._get_snmp_version_int(ctxt, new_config.get("version")) if version_int == constants.SNMP_V2_INT or \ version_int == constants.SNMP_V1_INT: community_string = cryptor.decode( new_config.get("community_string")) community_string = encodeutils.to_utf8(community_string) community_index = self._get_community_index(storage_id) config.addV1System(self.snmp_engine, community_index, community_string, contextName=community_string) else: username = new_config.get("username") engine_id = new_config.get("engine_id") if engine_id: engine_id = v2c.OctetString(hexValue=engine_id) auth_key = new_config.get("auth_key") auth_protocol = new_config.get("auth_protocol") privacy_key = new_config.get("privacy_key") privacy_protocol = new_config.get("privacy_protocol") if auth_key: auth_key = encodeutils.to_utf8(cryptor.decode(auth_key)) if privacy_key: privacy_key = encodeutils.to_utf8( cryptor.decode(privacy_key)) config.addV3User( self.snmp_engine, userName=username, authKey=auth_key, privKey=privacy_key, authProtocol=self._get_usm_auth_protocol(ctxt, auth_protocol), privProtocol=self._get_usm_priv_protocol(ctxt, privacy_protocol), securityEngineId=engine_id) LOG.info("Add snmp trap config for storage: %s successfully.", storage_id) except Exception as e: msg = six.text_type(e) LOG.error("Failed to add snmp trap config for storage: %s. " "Reason: %s", storage_id, msg) raise e
def setTrapReceiver(self, host, community): config.addV1System(self._snmpEngine, 'nms-area', community) config.addVacmUser(self._snmpEngine, 2, 'nms-area', 'noAuthNoPriv', notifySubTree=(1, 3, 6, 1, 4, 1)) config.addTargetParams(self._snmpEngine, 'nms-creds', 'nms-area', 'noAuthNoPriv', 1) config.addTargetAddr(self._snmpEngine, 'my-nms', udp.domainName, (host, 162), 'nms-creds', tagList='all-my-managers') config.addNotificationTarget(self._snmpEngine, 'test-notification', 'my-filter', 'all-my-managers', 'trap')
def __init__(self, ip, port, community='public'): self.LISTENER = ip self.LISTENER_PORT = port self.snmpEngine = engine.SnmpEngine() self.trap_sources = [] self.community = community self.traps = {} config.addTransport( self.snmpEngine, udp.domainName + (1, ), udp.UdpTransport().openServerMode( (self.LISTENER, self.LISTENER_PORT))) print('Starting SNMP server on %s port %s with community %s.' % (self.LISTENER, self.LISTENER_PORT, community)) config.addV1System(self.snmpEngine, 'testindex', community) self.stopped = False
def run(self): """Run collector and start processing incoming traps""" config.addSocketTransport( self.snmp_engine, udp.domainName + (1, ), udp.UdpTransport().openServerMode(("0.0.0.0", 162)), ) config.addV1System(self.snmp_engine, "new", "public") config.addContext(self.snmp_engine, "") ntfrcv.NotificationReceiver(self.snmp_engine, self.process_trap) self.snmp_engine.transportDispatcher.jobStarted(1) try: self.snmp_engine.transportDispatcher.runDispatcher() except Exception: self.snmp_engine.transportDispatcher.closeDispatcher() raise
def setTrapReceiver(self, host, community): """Send traps to the host using community string community """ config.addV1System(self._snmpEngine, 'nms-area', community) config.addVacmUser(self._snmpEngine, 2, 'nms-area', 'noAuthNoPriv', notifySubTree=(1,3,6,1,4,1)) config.addTargetParams(self._snmpEngine, 'nms-creds', 'nms-area', 'noAuthNoPriv', 1) config.addTargetAddr(self._snmpEngine, 'my-nms', udp.domainName, (host, 162), 'nms-creds', tagList='all-my-managers') #set last parameter to 'notification' to have it send #informs rather than unacknowledged traps config.addNotificationTarget( self._snmpEngine, 'test-notification', 'my-filter', 'all-my-managers', 'trap')
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
def __init__(self): self.unReadyNodes = list() self.identifiers = dict() self.snmpEngine = engine.SnmpEngine() self.bcmdgen = cmdgen.BulkCommandGenerator() self.snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher()) config.addV1System(self.snmpEngine, 'test-agent', SNMP_COMMUNITY) config.addTargetParams(self.snmpEngine, 'myParams', 'test-agent', 'noAuthNoPriv', 1) config.addSocketTransport( self.snmpEngine, udp.domainName, udp.UdpTwistedTransport().openClientMode() ) self.carbonFact = CarbonFactory(self) reactor.connectTCP(GRAPHITE_HOST, 2003, self.carbonFact)
def __init__(self): self.snmpEngine = engine.SnmpEngine() config.addSocketTransport( self.snmpEngine, udp.domainName, udp.UdpSocketTransport().openServerMode(('0.0.0.0', 162)) ) config.addV1System(self.snmpEngine, 'test-agent', 'public') config.addV3User( self.snmpEngine, 'test-user', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' # '80004fb81c3dafe69' # ContextEngineID of Notification Originator ) # Apps registration ntfrcv.NotificationReceiver(self.snmpEngine, self.recvcallback) self.snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish self.snmpEngine.transportDispatcher.runDispatcher()
def main(argv): # Create SNMP engine instance snmpEngine = engine.SnmpEngine() dispatcher = TornadoDispatcher() snmpEngine.registerTransportDispatcher(dispatcher) # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # UDP/IPv4 config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, (argv[0], 161), 'my-creds', timeout=3.0, retryCount=1 ) cbCtx = dict(dispatcher=dispatcher) cmdGen = cmdgen.GetCommandGenerator() cmdGen.sendReq( snmpEngine, 'my-router', ( ('1.3.6.1.2.1.1.1.0', None), ), cbFun, cbCtx ) IOLoop.instance().start()
def run(self): snmpEngine = engine.SnmpEngine() config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', self.__listening_port)) ) config.addV1System( snmpEngine, 'my-area', 'public', contextName='my-context') config.addVacmUser(snmpEngine=snmpEngine, securityModel=2, securityName='my-area', securityLevel='noAuthNoPriv', readSubTree=SNMPAgentResponder.OID_PREFIX, writeSubTree=(), notifySubTree=()) snmpContext = context.SnmpContext(snmpEngine) snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name self.__responder # Management Instrumentation ) cmdrsp.GetCommandResponder(snmpEngine, snmpContext) snmpEngine.transportDispatcher.jobStarted(1) self.__barrier.wait() # TODO with statement here! try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise
def __init__(self, mibObjects): # Each SNMP-based application has an engine self._snmpEngine = engine.SnmpEngine() # Open a UDP socket to listen for snmp requests (requset sudo command) config.addSocketTransport(self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('', 161))) config.addV1System(self._snmpEngine, 'agent', 'public') # add a v2 user with the community string public config.addVacmUser(self._snmpEngine, 2, 'agent', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 4, 1), writeSubTree=(1, 3, 6, 1, 4, 1)) # each app has one or more contexts self._snmpContext = context.SnmpContext(self._snmpEngine) # the builder is used to load mibs. tell it to look in the # current directory for our new MIB. We'll also use it to # export our symbols later mibBuilder = self._snmpContext.getMibInstrum().getMibBuilder() mibSources = mibBuilder.getMibSources() + (builder.DirMibSource('.'),) mibBuilder.setMibSources(*mibSources) # our variables will subclass this since we only have scalar types # can't load this type directly, need to import it (MibTable, MibTableRow, MibTableColumn, MibScalarInstance) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibScalarInstance') # import and maintain Table maintaintable = maintainTableThread(0, mibObjects, mibBuilder, MibScalarInstance) maintaintable.start() # tell pysnmp to respotd to get, getnext, and getbulk cmdrsp.GetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.SetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.NextCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.BulkCommandResponder(self._snmpEngine, self._snmpContext)
def v1TargetName( self, engine, ip, port=161, community='public', snmpVersion='2', ): """Find/create target name for v1/v2 connection to given agent""" key = (community,snmpVersion=='1') paramName = self._v1ParamCache.get( key ) if paramName is None: nameID = self._newV1Name() name = 'v1sys-%s'%(nameID) config.addV1System(engine, name, community) paramName = 'v1param-%s'%(nameID) if snmpVersion == '1': version = 0 else: version = 1 config.addTargetParams( engine, paramName, name, 'noAuthNoPriv', version ) self._v1ParamCache[ key ] = paramName return self._targetName( engine, ip, port, paramName )
def __init__(self, mibObjects): self._snmpEngine = engine.SnmpEngine() config.addSocketTransport(self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('',165))) config.addV1System(self._snmpEngine,"my-read-area","public") config.addV1System(self._snmpEngine,"my-write-area","private") config.addVacmUser(self._snmpEngine, 2,"my-read-area",'noAuthNoPriv',readSubTree=(1,3,6,1,4,1)) config.addVacmUser(self._snmpEngine, 2,"my-write-area",'noAuthNoPriv',readSubTree=(1,3,6,1,4,1), writeSubTree=(1,3,6,1,4,1)) self._snmpContext = context.SnmpContext(self._snmpEngine) mibBuilder = self._snmpContext.getMibInstrum().getMibBuilder() mibSources = mibBuilder.getMibSources()+(builder.DirMibSource('.'),)+(builder.DirMibSource('./pysnmp_mibs'),) mibBuilder.setMibSources(*mibSources) MibScalarInstance, = mibBuilder.importSymbols('SNMPv2-SMI','MibScalarInstance') for mibObject in mibObjects: nextVar, = mibBuilder.importSymbols(mibObject.mibName, mibObject.objectType) instance = createVariable(MibScalarInstance, mibObject.valueGetFunc, mibObject.valueSetFunc, nextVar.name, (0,), nextVar.syntax) instanceDict ={ str(nextVar.name)+"Instance":instance } mibBuilder.exportSymbols(mibObject.mibName, **instanceDict) cmdrsp.GetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.NextCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.BulkCommandResponder(self._snmpEngine, self._snmpContext)
# Optionally enable stdout debugging #debug.setLogger(debug.Debug('all')) # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Setup transport endpoint config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openServerMode(('127.0.0.1', 162)) ) # v1/2 setup config.addV1System(snmpEngine, 'test-agent', 'public') # v3 setup config.addV3User( snmpEngine, 'test-user', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' # '\x80\x00\x4f\xb8\x1c\x3d\xaf\xe6' # ContextEngineID of # Notification Originator ) # Callback function for receiving notifications def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds,
def configure(self, snmpEngine, authData, transportTarget, *options): cache = self._getCache(snmpEngine) if isinstance(authData, CommunityData): if authData.communityIndex not in cache['auth']: config.addV1System( snmpEngine, authData.communityIndex, authData.communityName, authData.contextEngineId, authData.contextName, authData.tag, authData.securityName ) cache['auth'][authData.communityIndex] = authData elif isinstance(authData, UsmUserData): authDataKey = authData.userName, authData.securityEngineId if authDataKey not in cache['auth']: config.addV3User( snmpEngine, authData.userName, authData.authProtocol, authData.authKey, authData.privProtocol, authData.privKey, authData.securityEngineId, securityName=authData.securityName ) cache['auth'][authDataKey] = authData else: raise error.PySnmpError('Unsupported authentication object') paramsKey = (authData.securityName, authData.securityLevel, authData.mpModel) if paramsKey in cache['parm']: paramsName, useCount = cache['parm'][paramsKey] cache['parm'][paramsKey] = paramsName, useCount + 1 else: paramsName = 'p%s' % self.nextID() config.addTargetParams( snmpEngine, paramsName, authData.securityName, authData.securityLevel, authData.mpModel ) cache['parm'][paramsKey] = paramsName, 1 if transportTarget.transportDomain in cache['tran']: transport, useCount = cache['tran'][transportTarget.transportDomain] transportTarget.verifyDispatcherCompatibility(snmpEngine) cache['tran'][transportTarget.transportDomain] = transport, useCount + 1 elif config.getTransport(snmpEngine, transportTarget.transportDomain): transportTarget.verifyDispatcherCompatibility(snmpEngine) else: transport = transportTarget.openClientMode() config.addTransport( snmpEngine, transportTarget.transportDomain, transport ) cache['tran'][transportTarget.transportDomain] = transport, 1 transportKey = (paramsName, transportTarget.transportDomain, transportTarget.transportAddr, transportTarget.tagList) if transportKey in cache['addr']: addrName, useCount = cache['addr'][transportKey] cache['addr'][transportKey] = addrName, useCount + 1 else: addrName = 'a%s' % self.nextID() config.addTargetAddr( snmpEngine, addrName, transportTarget.transportDomain, transportTarget.transportAddr, paramsName, transportTarget.timeout * 100, transportTarget.retries, transportTarget.tagList ) cache['addr'][transportKey] = addrName, 1 return addrName, paramsName
Functionally similar to: | $ snmptrap -v2c -c public demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 """ # from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, "my-area", "public") # 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.addTransport(snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()) # Create named target config.addTargetAddr(snmpEngine, "my-nms", udp.domainName, ("195.218.195.228", 162), "my-creds") # *** SNMP engine configuration is complete by this line *** # Create SNMP v2c TRAP PDU with defaults trapPDU = v2c.TrapPDU()
snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode(('127.0.0.1', 162)) ) # UDP over IPv4, second listening interface/port config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openServerMode(('127.0.0.1', 2162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print('Notification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun)
# $ snmpset -v1 -c private -ObentU 195.218.195.228:161 1.3.6.1.2.1.1.9.1.3.1 s 'my value' 1.3.6.1.2.1.1.9.1.4.1 t 123 # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1 setup # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'private') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0) # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() )
# Manager section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openClientMode() ) # # SNMPv2c setup (Agent role) # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # # SNMPv1 setup (Manager role) # # SecurityName <-> CommunityName <-> Transport mapping config.addV1System(snmpEngine, 'distant-area', 'public', transportTag='distant') # # Transport target used by Manager # # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'distant-agent-auth', 'distant-area', 'noAuthNoPriv', 0)
# * to a Manager at 127.0.0.1:162 # * with TRAP ID 'coldStart' specified as an OID # * include managed objects information: # 1.3.6.1.2.1.1.1.0 = 'Example Notificator' # 1.3.6.1.2.1.1.5.0 = 'Notificator Example' # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping (+ transport binding) config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers') # 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.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('127.0.0.1', 162), 'my-creds',
def __init__(self, host, port, mibpaths): self.oid_mapping = {} self.databus_mediator = DatabusMediator(self.oid_mapping) # mapping between OID and databus keys # Create SNMP engine self.snmpEngine = engine.SnmpEngine() # path to custom mibs mibBuilder = self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder mibSources = mibBuilder.getMibSources() for mibpath in mibpaths: mibSources += (builder.DirMibSource(mibpath),) mibBuilder.setMibSources(*mibSources) # Transport setup udp_sock = gevent.socket.socket(gevent.socket.AF_INET, gevent.socket.SOCK_DGRAM) udp_sock.setsockopt(gevent.socket.SOL_SOCKET, gevent.socket.SO_BROADCAST, 1) udp_sock.bind((host, port)) self.server_port = udp_sock.getsockname()[1] # UDP over IPv4 self.addSocketTransport( self.snmpEngine, udp.domainName, udp_sock ) # SNMPv1 config.addV1System(self.snmpEngine, 'public-read', 'public') # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( self.snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( self.snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtocol, 'authkey1' ) # user: usr-sha-aes128, auth: SHA, priv AES/128 config.addV3User( self.snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(self.snmpEngine, 1, 'public-read', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 2, 'public-read', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-md5-des', 'authPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-sha-none', 'authNoPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-sha-aes128', 'authPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(self.snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context self.resp_app_get = conpot_cmdrsp.c_GetCommandResponder(self.snmpEngine, snmpContext, self.databus_mediator, host, port) self.resp_app_set = conpot_cmdrsp.c_SetCommandResponder(self.snmpEngine, snmpContext, self.databus_mediator, host, port) self.resp_app_next = conpot_cmdrsp.c_NextCommandResponder(self.snmpEngine, snmpContext, self.databus_mediator, host, port) self.resp_app_bulk = conpot_cmdrsp.c_BulkCommandResponder(self.snmpEngine, snmpContext, self.databus_mediator, host, port)
# Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv1 setup # SecurityName <-> CommunityName mapping. # Here we configure two distinct CommunityName's to control read and write # operations. config.addV1System(snmpEngine, 'my-read-area', 'public') config.addV1System(snmpEngine, 'my-write-area', 'private') # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 1, 'my-read-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 1, 'my-write-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) # Run Twisted main loop
def cfgCmdGen(self, authData, transportTarget, tagList=null): if authData not in self.__knownAuths: if isinstance(authData, CommunityData): config.addV1System( self.snmpEngine, authData.securityName, authData.communityName, authData.contextEngineId, authData.contextName, tagList ) elif isinstance(authData, UsmUserData): config.addV3User( self.snmpEngine, authData.securityName, authData.authProtocol, authData.authKey, authData.privProtocol, authData.privKey, authData.contextEngineId ) else: raise error.PySnmpError('Unsupported authentication object') self.__knownAuths[authData] = 1 k = authData.securityName, authData.securityLevel, authData.mpModel if k in self.__knownParams: paramsName = self.__knownParams[k] else: paramsName = 'p%s' % nextID() config.addTargetParams( self.snmpEngine, paramsName, authData.securityName, authData.securityLevel, authData.mpModel ) self.__knownParams[k] = paramsName if transportTarget.transportDomain not in self.__knownTransports: transport = transportTarget.openClientMode() config.addSocketTransport( self.snmpEngine, transportTarget.transportDomain, transport ) self.__knownTransports[transportTarget.transportDomain] = transport k = paramsName, transportTarget, tagList if k in self.__knownTransportAddrs: addrName = self.__knownTransportAddrs[k] else: addrName = 'a%s' % nextID() config.addTargetAddr( self.snmpEngine, addrName, transportTarget.transportDomain, transportTarget.transportAddr, paramsName, transportTarget.timeout * 100, transportTarget.retries, tagList ) self.__knownTransportAddrs[k] = addrName return addrName, paramsName