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 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 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 __init__(self, objects): self._snmpEngine = engine.SnmpEngine() config.addSocketTransport( self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((_addr, _port))) config.addV3User(self._snmpEngine,_account,config.usmHMACMD5AuthProtocol,_auth_key,config.usmDESPrivProtocol,_priv_key) config.addVacmUser(self._snmpEngine, 3, _account, "authPriv",(1,3,6,1,4,1), (1,3,6,1,4,1)) self._snmpContext = context.SnmpContext(self._snmpEngine) #builder create mibBuilder = self._snmpContext.getMibInstrum().getMibBuilder() mibSources = mibBuilder.getMibSources() + (builder.DirMibSource('.'),)+(builder.DirMibSource(filepath),) mibBuilder.setMibSources(*mibSources) MibScalarInstance, = mibBuilder.importSymbols('SNMPv2-SMI','MibScalarInstance') for mibObject in objects: nextVar, = mibBuilder.importSymbols(mibObject.mibName, mibObject.objectType) instance = createVariable(MibScalarInstance, mibObject.valueGetFunc, nextVar.name, (0,), nextVar.syntax) #need to export as <var name>Instance instanceDict = {str(nextVar.name)+"Instance":instance} mibBuilder.exportSymbols(mibObject.mibName, **instanceDict) 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 configure(self, snmpEngine, authData, transportTarget, notifyType, contextName, **options): cache = self._getCache(snmpEngine) notifyName = None # Create matching transport tags if not given by user. Not good! if not transportTarget.tagList: transportTarget.tagList = str( hash((authData.securityName, transportTarget.transportAddr))) if isinstance(authData, CommunityData) and not authData.tag: authData.tag = transportTarget.tagList.split()[0] addrName, paramsName = self._cmdGenLcdCfg.configure( snmpEngine, authData, transportTarget, contextName, **options) tagList = transportTarget.tagList.split() if not tagList: tagList = [''] for tag in tagList: notifyNameKey = paramsName, tag, notifyType if notifyNameKey in cache['name']: notifyName, paramsName, useCount = cache['name'][notifyNameKey] cache['name'][ notifyNameKey] = notifyName, paramsName, useCount + 1 else: notifyName = 'n%s' % self.nextID() config.addNotificationTarget(snmpEngine, notifyName, paramsName, tag, notifyType) cache['name'][notifyNameKey] = notifyName, paramsName, 1 authDataKey = authData.securityName, authData.securityModel, authData.securityLevel, contextName if authDataKey in cache['auth']: authDataX, subTree, useCount = cache['auth'][authDataKey] cache['auth'][authDataKey] = authDataX, subTree, useCount + 1 else: subTree = (1, 3, 6) config.addVacmUser(snmpEngine, authData.securityModel, authData.securityName, authData.securityLevel, (), (), subTree, contextName=contextName) cache['auth'][authDataKey] = authData, subTree, 1 return notifyName
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 configure(self, snmpEngine, authData, transportTarget, notifyType, contextName, **options): cache = self._getCache(snmpEngine) notifyName = None # Create matching transport tags if not given by user. Not good! if not transportTarget.tagList: transportTarget.tagList = str( hash((authData.securityName, transportTarget.transportAddr)) ) if isinstance(authData, CommunityData) and not authData.tag: authData.tag = transportTarget.tagList.split()[0] addrName, paramsName = self._cmdGenLcdCfg.configure( snmpEngine, authData, transportTarget, contextName, **options) tagList = transportTarget.tagList.split() if not tagList: tagList = [''] for tag in tagList: notifyNameKey = paramsName, tag, notifyType if notifyNameKey in cache['name']: notifyName, paramsName, useCount = cache['name'][notifyNameKey] cache['name'][notifyNameKey] = notifyName, paramsName, useCount + 1 else: notifyName = 'n%s' % self.nextID() config.addNotificationTarget( snmpEngine, notifyName, paramsName, tag, notifyType) cache['name'][notifyNameKey] = notifyName, paramsName, 1 authDataKey = authData.securityName, authData.securityModel, authData.securityLevel, contextName if authDataKey in cache['auth']: authDataX, subTree, useCount = cache['auth'][authDataKey] cache['auth'][authDataKey] = authDataX, subTree, useCount + 1 else: subTree = (1, 3, 6) config.addVacmUser( snmpEngine,authData.securityModel, authData.securityName, authData.securityLevel, (), (), subTree, contextName=contextName) cache['auth'][authDataKey] = authData, subTree, 1 return notifyName
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 _add_user_permission(self, OID): """ Add user permission to OID - readOnly """ OID = tuple(int(x) for x in OID.split(".")) if self.users: for user in self.users: print("add user permission %s %s " % (str(user), str(OID))) config.addVacmUser(self.snmpEngine, 3, str(user[0]), str(user[3]), OID) else: # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(self.snmpEngine, 1, "my-read-area", "noAuthNoPriv", OID)
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 _add_user_permission(self, OID): """ Add user permission to OID - readOnly """ OID = tuple(int(x) for x in OID.split('.')) if self.users: for user in self.users: print('add user permission %s %s ' % (str(user), str(OID))) config.addVacmUser(self.snmpEngine, 3, str(user[0]), str(user[3]), OID) else: #Allow full MIB access for this user / securityModels at VACM config.addVacmUser(self.snmpEngine, 1, 'my-read-area', 'noAuthNoPriv', OID)
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 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 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 __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 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, host, port, mibObjects): self._snmpEngine = engine.SnmpEngine() config.addSocketTransport( self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((host, port))) config.addV1System(self._snmpEngine, "agent", "publick") # password config.addV1System(self._snmpEngine, 'my-write-area', 'private') config.addVacmUser(self._snmpEngine, 2, "agent", "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('.'), ) mibBuilder.setMibSources(*mibSources) MibScalarInstance, = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') for mibObject in mibObjects: nextVar, = mibBuilder.importSymbols(mibObject.mibName, mibObject.objectType) instance = createVariable(MibScalarInstance, mibObject.valueFunc, 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.SetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.NextCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.BulkCommandResponder(self._snmpEngine, self._snmpContext)
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 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, objects): self._snmpEngine = engine.SnmpEngine() config.addSocketTransport( self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((_addr, _port))) config.addV3User(self._snmpEngine, _account, config.usmHMACMD5AuthProtocol, _auth_key, config.usmDESPrivProtocol, _priv_key) config.addVacmUser(self._snmpEngine, 3, _account, "authPriv", (1, 3, 6, 1, 4, 1), (1, 3, 6, 1, 4, 1)) self._snmpContext = context.SnmpContext(self._snmpEngine) #builder create mibBuilder = self._snmpContext.getMibInstrum().getMibBuilder() mibSources = mibBuilder.getMibSources() + ( builder.DirMibSource('.'), ) + (builder.DirMibSource(filepath), ) mibBuilder.setMibSources(*mibSources) MibScalarInstance, = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') for mibObject in objects: nextVar, = mibBuilder.importSymbols(mibObject.mibName, mibObject.objectType) instance = createVariable(MibScalarInstance, mibObject.valueGetFunc, nextVar.name, (0, ), nextVar.syntax) #need to export as <var name>Instance instanceDict = {str(nextVar.name) + "Instance": instance} mibBuilder.exportSymbols(mibObject.mibName, **instanceDict) 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 __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 __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)
config.addNotificationTarget( # snmpEngine, 'my-notification', 'my-creds', 'all-my-managers', 'trap' snmpEngine, 'my-notification', 'my-creds', 'all-my-managers', 'inform') # # Notifications carry potentially confidential information from # the Agent. Therefore access control is to be setup allowing # NotificationOriginator access to certain portions of Agent MIB. # config.addContext(snmpEngine, '') # SNMPv1 config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) # SNMPv2c config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) # SNMPv3 config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (), (), (1, 3, 6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authPriv', (), (), (1, 3, 6)) config.addVacmUser(snmpEngine, 3, 'usr-none-none', 'authPriv', (), (), (1, 3, 6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-aes192', 'authPriv', (), (), (1, 3, 6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-aes256', 'authPriv', (), (), (1, 3, 6)) config.addVacmUser(snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (), (), (1, 3, 6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-3des', 'authPriv', (), (),
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' ) )
# Transport setup # UDP over IPv4 config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode( (Comm['ipAddress'], int(Comm['snmpPort'])))) # SNMPv2c setup # SecurityName <-> CommunityName mapping. config.addV1System(snmpEngine, 'my-area', Comm['snmpCommunity']) # Allow read MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, int(Comm['snmpVersion']), 'my-area', 'noAuthNoPriv', sysOID, sysOID) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # --- create custom Managed Object Instance --- mibBuilder = snmpContext.getMibInstrum().getMibBuilder() MibScalar, MibScalarInstance = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalar', 'MibScalarInstance') class MyStaticMibScalarInstance(MibScalarInstance): def setValue(self, value, name, idx): self.nm = tuple(map(str, name))
def _setup(self, q): """Setup a new agent in a separate process. The port the agent is listening too will be returned using the provided queue. """ port = random.randrange(22000, 22989) snmpEngine = engine.SnmpEngine() if self.ipv6: config.addSocketTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(('::1', port))) else: config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', port))) # Community is public and MIB is writable config.addV1System(snmpEngine, 'read-write', 'public') config.addVacmUser(snmpEngine, 1, 'read-write', 'noAuthNoPriv', (1, 3, 6), (1, 3, 6)) config.addVacmUser(snmpEngine, 2, 'read-write', 'noAuthNoPriv', (1, 3, 6), (1, 3, 6)) config.addV3User(snmpEngine, 'read-write', config.usmHMACMD5AuthProtocol, 'authpass', config.usmAesCfb128Protocol, 'privpass') config.addVacmUser(snmpEngine, 3, 'read-write', 'authPriv', (1, 3, 6), (1, 3, 6)) # Build MIB def stringToOid(string): return [ord(x) for x in string] def flatten(*args): result = [] for el in args: if isinstance(el, (list, tuple)): for sub in el: result.append(sub) else: result.append(el) return tuple(result) snmpContext = context.SnmpContext(snmpEngine) mibBuilder = snmpContext.getMibInstrum().getMibBuilder() (MibTable, MibTableRow, MibTableColumn, MibScalar, MibScalarInstance) = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibScalar', 'MibScalarInstance') mibBuilder.exportSymbols( '__MY_SNMPv2_MIB', # SNMPv2-MIB::sysDescr MibScalar((1, 3, 6, 1, 2, 1, 1, 1), v2c.OctetString()), MibScalarInstance((1, 3, 6, 1, 2, 1, 1, 1), (0, ), v2c.OctetString("Snimpy Test Agent"))) mibBuilder.exportSymbols( '__MY_IF_MIB', # IF-MIB::ifNumber MibScalar((1, 3, 6, 1, 2, 1, 2, 1), v2c.Integer()), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 1), (0, ), v2c.Integer(3)), # IF-MIB::ifTable MibTable((1, 3, 6, 1, 2, 1, 2, 2)), MibTableRow((1, 3, 6, 1, 2, 1, 2, 2, 1)).setIndexNames( (0, '__MY_IF_MIB', 'ifIndex')), # IF-MIB::ifIndex MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (1, ), v2c.Integer(1)), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (2, ), v2c.Integer(2)), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (3, ), v2c.Integer(3)), # IF-MIB::ifDescr MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), v2c.OctetString()), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (1, ), v2c.OctetString("lo")), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (2, ), v2c.OctetString("eth0")), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (3, ), v2c.OctetString("eth1")), # IF-MIB::ifType MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), v2c.Integer()), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (1, ), v2c.Integer(24)), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (2, ), v2c.Integer(6)), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (3, ), v2c.Integer(6)), # IF-MIB::ifIndex ifIndex=MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), v2c.Integer())) mibBuilder.exportSymbols( '__MY_SNIMPY-MIB', # SNIMPY-MIB::snimpyIpAddress MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 1), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 1), (0, ), v2c.OctetString("AAAA")), # SNIMPY-MIB::snimpyString MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 2), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 2), (0, ), v2c.OctetString("bye")), # SNIMPY-MIB::snimpyInteger MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 3), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 3), (0, ), v2c.Integer(19)), # SNIMPY-MIB::snimpyEnum MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 4), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 4), (0, ), v2c.Integer(2)), # SNIMPY-MIB::snimpyObjectId MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 5), v2c.ObjectIdentifier()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 5), (0, ), v2c.ObjectIdentifier((1, 3, 6, 4454, 0, 0))), # SNIMPY-MIB::snimpyBoolean MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 6), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 6), (0, ), v2c.Integer(1)), # SNIMPY-MIB::snimpyCounter MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 7), v2c.Counter32()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 7), (0, ), v2c.Counter32(47)), # SNIMPY-MIB::snimpyGauge MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 8), v2c.Gauge32()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 8), (0, ), v2c.Gauge32(18)), # SNIMPY-MIB::snimpyTimeticks MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 9), v2c.TimeTicks()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 9), (0, ), v2c.TimeTicks(12111100)), # SNIMPY-MIB::snimpyCounter64 MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 10), v2c.Counter64()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 10), (0, ), v2c.Counter64(2**48 + 3)), # SNIMPY-MIB::snimpyBits MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 11), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 11), (0, ), v2c.OctetString(b"\xa0")), # SNIMPY-MIB::snimpyMacAddress MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 15), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 15), (0, ), v2c.OctetString(b"\x11\x12\x13\x14\x15\x16")), # SNIMPY-MIB::snimpyMacAddressInvalid MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 16), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 16), (0, ), v2c.OctetString(b"\xf1\x12\x13\x14\x15\x16")), # SNIMPY-MIB::snimpyIndexTable MibTable((1, 3, 6, 1, 2, 1, 45121, 2, 3)), MibTableRow((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1)).setIndexNames( (0, "__MY_SNIMPY-MIB", "snimpyIndexVarLen"), (0, "__MY_SNIMPY-MIB", "snimpyIndexOidVarLen"), (0, "__MY_SNIMPY-MIB", "snimpyIndexFixedLen"), (1, "__MY_SNIMPY-MIB", "snimpyIndexImplied")), # SNIMPY-MIB::snimpyIndexInt MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row1'), 3, 1, 2, 3, stringToOid('alpha5'), stringToOid('end of row1')), v2c.Integer(4571)), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row2'), 4, 1, 0, 2, 3, stringToOid('beta32'), stringToOid('end of row2')), v2c.Integer(78741)), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row3'), 4, 120, 1, 2, 3, stringToOid('gamma7'), stringToOid('end of row3')), v2c.Integer(4110)), # SNIMPY-MIB::snimpyInvalidTable MibTable((1, 3, 6, 1, 2, 1, 45121, 2, 5)), MibTableRow((1, 3, 6, 1, 2, 1, 45121, 2, 5, 1)).setIndexNames( (0, "__MY_SNIMPY-MIB", "snimpyInvalidIndex")), # SNIMPY-MIB::snimpyInvalidDescr MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 2), (1, ), v2c.OctetString(b"Hello")), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 2), (2, ), v2c.OctetString(b"\xf1\x12\x13\x14\x15\x16")), # Indexes snimpyIndexVarLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), v2c.OctetString()).setMaxAccess("noaccess"), snimpyIndexIntIndex=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 2), v2c.Integer()).setMaxAccess("noaccess"), snimpyIndexOidVarLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 3), v2c.ObjectIdentifier()).setMaxAccess("noaccess"), snimpyIndexFixedLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 4), v2c.OctetString().setFixedLength(6)).setMaxAccess("noaccess"), snimpyIndexImplied=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 5), v2c.OctetString()).setMaxAccess("noaccess"), snimpyIndexInt=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), v2c.Integer()).setMaxAccess("readwrite"), snimpyInvalidIndex=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 1), v2c.Integer()).setMaxAccess("noaccess"), snimpyInvalidDescr=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 2), v2c.OctetString()).setMaxAccess("readwrite")) # Start agent cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) q.put(port) snmpEngine.transportDispatcher.jobStarted(1) snmpEngine.transportDispatcher.runDispatcher()
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, 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) self.resp_app_set = conpot_cmdrsp.c_SetCommandResponder( self.snmpEngine, snmpContext, self.databus_mediator) self.resp_app_next = conpot_cmdrsp.c_NextCommandResponder( self.snmpEngine, snmpContext, self.databus_mediator) self.resp_app_bulk = conpot_cmdrsp.c_BulkCommandResponder( self.snmpEngine, snmpContext, self.databus_mediator)
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 [
config.addTargetAddr(snmpEngine, 'my-nms-2', udp.domainName, ('127.0.0.1', 162), 'my-creds-2', 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 (2&3), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (), (), (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) # Error/confirmation receiver def cbFun(sendRequestHandle, errorIndication, cbCtx): print('Notification %s, status - %s' %
def setup_access(self): auth_mapping = {enums.AuthProtocol.MD5: config.usmHMACMD5AuthProtocol, enums.AuthProtocol.SHA: config.usmHMACSHAAuthProtocol, None: config.usmNoAuthProtocol} priv_mapping = {enums.PrivProtocol.DES: config.usmDESPrivProtocol, enums.PrivProtocol.AES: config.usmAesCfb128Protocol, None: config.usmNoPrivProtocol} if len(self.access_config.items()) == 0: raise snmp_ex.NoUserExistsError( 'No v2 community or v3 user exists') for name, obj in self.access_config.items(): if obj.mode == enums.UserVersion.V3: try: if obj.priv_protocol is None: config.addV3User(self.engine, name, auth_mapping[obj.auth_protocol], obj.auth_key.raw) LOG.info( 'Succeed to add v3 user: {} for engine: {}, ' 'auth protocol: {}, ' 'priv protocol: {}'.format(name, self.engine_id, obj.auth_protocol, None)) else: config.addV3User(self.engine, name, auth_mapping[obj.auth_protocol], obj.auth_key.raw, priv_mapping[obj.priv_protocol], obj.priv_key.raw) LOG.info( 'Succeed to add v3 user: {} for engine: {}, ' 'auth protocol: {}, ' 'priv protocol: {}'.format(name, self.engine_id, obj.auth_protocol, obj.priv_protocol)) config.addVacmUser(self.engine, 3, name, obj.security_level.index, READ_SUB_TREE, WRITE_SUB_TREE) except smi_ex.WrongValueError: LOG.exception( 'Failed to add v3 user: {} for engine: {}, ' 'auth protocol: {}, ' 'priv protocol: {}'.format(name, self.engine_id, obj.auth_protocol, None)) else: security_level = enums.SecurityLevel.NO_AUTH_NO_PRIV.index try: config.addV1System(self.engine, name, obj.community) config.addVacmUser(self.engine, 2, name, security_level, READ_SUB_TREE, WRITE_SUB_TREE) LOG.info('Succeed to add v2 user: {} for engine: {}, ' 'community: {}'.format(name, self.engine_id, obj.community)) except smi_ex.WrongValueError: LOG.exception('Failed to add v2 user: {} for engine: {}, ' 'community: {}'.format(name, self.engine_id, obj.community))
snmpEngine, 'usr-md5-3des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usm3DESEDEPrivProtocol, 'privkey1' ) # # Access control (VACM) setup # # Configure VACM from the scratch # default context config.addContext(snmpEngine, '') # allow full MIB access for each user config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (1,3,6), (1,3,6)) config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1,3,6), (1,3,6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1,3,6), (1,3,6)) # # CommandResponder could serve multiple independent MIB trees # selected by ContextName parameter. The default ContextName is # an empty string, this is where SNMP engine's LCD also lives. # snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext)
# UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv3/USM setup # user: usr-none-none, auth: NONE, priv NONE config.addV3User( snmpEngine, 'usr-none-none' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-none-none', 'noAuthNoPriv', (1,3,6,1,2,1), (1,3,6,1,2,1)) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # Very basic Management Instrumentation Controller without # any Managed Objects attached. It supports only GET's and # always echos request var-binds in response. class EchoMibInstrumController(instrum.AbstractMibInstrumController): def readVars(self, vars, acInfo=(None, None)): return [ (ov[0], v2c.OctetString('You queried OID %s' % ov[0])) for ov in vars] # Create a custom Management Instrumentation Controller and register at # SNMP Context under ContextName 'my-context' snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name
def _setup(self, q, port): """Setup a new agent in a separate process. The port the agent is listening too will be returned using the provided queue. """ snmpEngine = engine.SnmpEngine() if self.ipv6: config.addSocketTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(('::1', port))) else: config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', port))) # Community is public and MIB is writable config.addV1System(snmpEngine, 'read-write', self.community) config.addVacmUser(snmpEngine, 1, 'read-write', 'noAuthNoPriv', (1, 3, 6), (1, 3, 6)) config.addVacmUser(snmpEngine, 2, 'read-write', 'noAuthNoPriv', (1, 3, 6), (1, 3, 6)) config.addV3User( snmpEngine, 'read-write', config.usmHMACMD5AuthProtocol, self.authpass, config.usmAesCfb128Protocol, self.privpass) config.addVacmUser(snmpEngine, 3, 'read-write', 'authPriv', (1, 3, 6), (1, 3, 6)) # Build MIB def stringToOid(string): return [ord(x) for x in string] def flatten(*args): result = [] for el in args: if isinstance(el, (list, tuple)): for sub in el: result.append(sub) else: result.append(el) return tuple(result) snmpContext = context.SnmpContext(snmpEngine) mibBuilder = snmpContext.getMibInstrum().getMibBuilder() (MibTable, MibTableRow, MibTableColumn, MibScalar, MibScalarInstance) = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibScalar', 'MibScalarInstance') class RandomMibScalarInstance(MibScalarInstance): previous_value = 0 def getValue(self, name, idx): self.previous_value += random.randint(1, 2000) return self.getSyntax().clone(self.previous_value) mibBuilder.exportSymbols( '__MY_SNMPv2_MIB', # SNMPv2-MIB::sysDescr MibScalar((1, 3, 6, 1, 2, 1, 1, 1), v2c.OctetString()), MibScalarInstance((1, 3, 6, 1, 2, 1, 1, 1), (0,), v2c.OctetString( "Snimpy Test Agent {0}".format( self.community))), # SNMPv2-MIB::sysObjectID MibScalar((1, 3, 6, 1, 2, 1, 1, 2), v2c.ObjectIdentifier()), MibScalarInstance((1, 3, 6, 1, 2, 1, 1, 2), (0,), v2c.ObjectIdentifier((1, 3, 6, 1, 4, 1, 9, 1, 1208)))) mibBuilder.exportSymbols( '__MY_IF_MIB', # IF-MIB::ifNumber MibScalar((1, 3, 6, 1, 2, 1, 2, 1), v2c.Integer()), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 1), (0,), v2c.Integer(3)), # IF-MIB::ifTable MibTable((1, 3, 6, 1, 2, 1, 2, 2)), MibTableRow((1, 3, 6, 1, 2, 1, 2, 2, 1)).setIndexNames( (0, '__MY_IF_MIB', 'ifIndex')), # IF-MIB::ifIndex MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (1,), v2c.Integer(1)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (2,), v2c.Integer(2)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (3,), v2c.Integer(3)), # IF-MIB::ifDescr MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), v2c.OctetString()), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (1,), v2c.OctetString("lo")), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (2,), v2c.OctetString("eth0")), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (3,), v2c.OctetString("eth1")), # IF-MIB::ifType MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), v2c.Integer()), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (1,), v2c.Integer(24)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (2,), v2c.Integer(6)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (3,), v2c.Integer(6)), # IF-MIB::ifInOctets MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 10), v2c.Integer()), RandomMibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 10), (1,), v2c.Gauge32()), RandomMibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 10), (2,), v2c.Gauge32()), RandomMibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 10), (3,), v2c.Gauge32()), # IF-MIB::ifRcvAddressTable MibTable((1, 3, 6, 1, 2, 1, 31, 1, 4)), MibTableRow((1, 3, 6, 1, 2, 1, 31, 1, 4, 1)).setIndexNames( (0, '__MY_IF_MIB', 'ifIndex'), (1, '__MY_IF_MIB', 'ifRcvAddressAddress')), # IF-MIB::ifRcvAddressStatus MibTableColumn((1, 3, 6, 1, 2, 1, 31, 1, 4, 1, 2), v2c.Integer()), MibScalarInstance( (1, 3, 6, 1, 2, 1, 31, 1, 4, 1, 2), flatten(2, 6, stringToOid("abcdef")), v2c.Integer(1)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 31, 1, 4, 1, 2), flatten(2, 6, stringToOid("ghijkl")), v2c.Integer(1)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 31, 1, 4, 1, 2), flatten(3, 6, stringToOid("mnopqr")), v2c.Integer(1)), # IF-MIB::ifRcvAddressType MibTableColumn((1, 3, 6, 1, 2, 1, 31, 1, 4, 1, 3), v2c.Integer()), MibScalarInstance( (1, 3, 6, 1, 2, 1, 31, 1, 4, 1, 3), flatten(2, 6, stringToOid("abcdef")), v2c.Integer(1)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 31, 1, 4, 1, 3), flatten(2, 6, stringToOid("ghijkl")), v2c.Integer(1)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 31, 1, 4, 1, 3), flatten(3, 6, stringToOid("mnopqr")), v2c.Integer(1)), # IF-MIB::ifIndex ifIndex=MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), v2c.Integer()), # IF-MIB::ifRcvAddressAddress ifRcvAddressAddress=MibTableColumn((1, 3, 6, 1, 2, 1, 31, 1, 4, 1, 1), v2c.OctetString())) args = ( '__MY_SNIMPY-MIB', # SNIMPY-MIB::snimpyIpAddress MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 1), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 1), (0,), v2c.OctetString("AAAA")), # SNIMPY-MIB::snimpyString MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 2), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 2), (0,), v2c.OctetString("bye")), # SNIMPY-MIB::snimpyInteger MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 3), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 3), (0,), v2c.Integer(19)), # SNIMPY-MIB::snimpyEnum MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 4), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 4), (0,), v2c.Integer(2)), # SNIMPY-MIB::snimpyObjectId MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 5), v2c.ObjectIdentifier()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 5), ( 0,), v2c.ObjectIdentifier((1, 3, 6, 4454, 0, 0))), # SNIMPY-MIB::snimpyBoolean MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 6), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 6), (0,), v2c.Integer(1)), # SNIMPY-MIB::snimpyCounter MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 7), v2c.Counter32()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 7), (0,), v2c.Counter32(47)), # SNIMPY-MIB::snimpyGauge MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 8), v2c.Gauge32()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 8), (0,), v2c.Gauge32(18)), # SNIMPY-MIB::snimpyTimeticks MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 9), v2c.TimeTicks()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 9), (0,), v2c.TimeTicks(12111100)), # SNIMPY-MIB::snimpyCounter64 MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 10), v2c.Counter64()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 10), (0,), v2c.Counter64(2 ** 48 + 3)), # SNIMPY-MIB::snimpyBits MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 11), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 11), (0,), v2c.OctetString(b"\xa0")), # SNIMPY-MIB::snimpyMacAddress MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 15), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 15), ( 0,), v2c.OctetString(b"\x11\x12\x13\x14\x15\x16")), # SNIMPY-MIB::snimpyMacAddressInvalid MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 16), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 16), ( 0,), v2c.OctetString(b"\xf1\x12\x13\x14\x15\x16")), # SNIMPY-MIB::snimpyIndexTable MibTable((1, 3, 6, 1, 2, 1, 45121, 2, 3)), MibTableRow( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1)).setIndexNames( (0, "__MY_SNIMPY-MIB", "snimpyIndexVarLen"), (0, "__MY_SNIMPY-MIB", "snimpyIndexOidVarLen"), (0, "__MY_SNIMPY-MIB", "snimpyIndexFixedLen"), (1, "__MY_SNIMPY-MIB", "snimpyIndexImplied")), # SNIMPY-MIB::snimpyIndexVarLen MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), flatten(4, stringToOid('row1'), 3, 1, 2, 3, stringToOid('alpha5'), stringToOid('end of row1')), v2c.OctetString(b"row1")), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), flatten(4, stringToOid('row2'), 4, 1, 0, 2, 3, stringToOid('beta32'), stringToOid('end of row2')), v2c.OctetString(b"row2")), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), flatten(4, stringToOid('row3'), 4, 120, 1, 2, 3, stringToOid('gamma7'), stringToOid('end of row3')), v2c.OctetString(b"row3")), # SNIMPY-MIB::snimpyIndexInt MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row1'), 3, 1, 2, 3, stringToOid('alpha5'), stringToOid('end of row1')), v2c.Integer(4571)), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row2'), 4, 1, 0, 2, 3, stringToOid('beta32'), stringToOid('end of row2')), v2c.Integer(78741)), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row3'), 4, 120, 1, 2, 3, stringToOid('gamma7'), stringToOid('end of row3')), v2c.Integer(4110)), # SNIMPY-MIB::snimpyInvalidTable MibTable((1, 3, 6, 1, 2, 1, 45121, 2, 5)), MibTableRow( (1, 3, 6, 1, 2, 1, 45121, 2, 5, 1)).setIndexNames( (0, "__MY_SNIMPY-MIB", "snimpyInvalidIndex")), # SNIMPY-MIB::snimpyInvalidDescr MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 2), (1,), v2c.OctetString(b"Hello")), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 2), (2,), v2c.OctetString(b"\xf1\x12\x13\x14\x15\x16"))) if self.emptyTable: args += ( # SNIMPY-MIB::snimpyEmptyTable MibTable((1, 3, 6, 1, 2, 1, 45121, 2, 6)), MibTableRow( (1, 3, 6, 1, 2, 1, 45121, 2, 6, 1)).setIndexNames( (0, "__MY_SNIMPY-MIB", "snimpyEmptyIndex"))) kwargs = dict( # Indexes snimpyIndexVarLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), v2c.OctetString( )), snimpyIndexIntIndex=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 2), v2c.Integer( )).setMaxAccess( "noaccess"), snimpyIndexOidVarLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 3), v2c.ObjectIdentifier( )).setMaxAccess( "noaccess"), snimpyIndexFixedLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 4), v2c.OctetString( ).setFixedLength( 6)).setMaxAccess( "noaccess"), snimpyIndexImplied=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 5), v2c.OctetString( )).setMaxAccess("noaccess"), snimpyIndexInt=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), v2c.Integer()).setMaxAccess("readwrite"), snimpyInvalidIndex=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 1), v2c.Integer()).setMaxAccess("noaccess"), snimpyInvalidDescr=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 2), v2c.OctetString()).setMaxAccess("readwrite") ) if self.emptyTable: kwargs.update(dict( snimpyEmptyIndex=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 6, 1, 1), v2c.Integer()).setMaxAccess("noaccess"), snimpyEmptyDescr=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 6, 1, 2), v2c.OctetString()).setMaxAccess("readwrite"))) mibBuilder.exportSymbols(*args, **kwargs) # Start agent cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) q.put(port) snmpEngine.transportDispatcher.jobStarted(1) snmpEngine.transportDispatcher.runDispatcher()
def _setup(self, q): """Setup a new agent in a separate process. The port the agent is listening too will be returned using the provided queue. """ port = random.randrange(22000, 22989) snmpEngine = engine.SnmpEngine() config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', port))) # Community is public and MIB is writable config.addV1System(snmpEngine, 'read-write', 'public') config.addVacmUser(snmpEngine, 1, 'read-write', 'noAuthNoPriv', (1, 3, 6), (1, 3, 6)) config.addVacmUser(snmpEngine, 2, 'read-write', 'noAuthNoPriv', (1, 3, 6), (1, 3, 6)) config.addV3User( snmpEngine, 'read-write', config.usmHMACMD5AuthProtocol, 'authpass', config.usmAesCfb128Protocol, 'privpass' ) config.addVacmUser(snmpEngine, 3, 'read-write', 'authPriv', (1, 3, 6), (1, 3, 6)) # Build MIB def stringToOid(string): return [ord(x) for x in string] def flatten(*args): result = [] for el in args: if isinstance(el, (list, tuple)): for sub in el: result.append(sub) else: result.append(el) return tuple(result) snmpContext = context.SnmpContext(snmpEngine) mibBuilder = snmpContext.getMibInstrum().getMibBuilder() (MibTable, MibTableRow, MibTableColumn, MibScalar, MibScalarInstance) = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibScalar', 'MibScalarInstance') mibBuilder.exportSymbols( '__MY_SNMPv2_MIB', # SNMPv2-MIB::sysDescr MibScalar((1, 3, 6, 1, 2, 1, 1, 1), v2c.OctetString()), MibScalarInstance((1, 3, 6, 1, 2, 1, 1, 1), (0,), v2c.OctetString("Snimpy Test Agent"))) mibBuilder.exportSymbols( '__MY_IF_MIB', # IF-MIB::ifNumber MibScalar((1, 3, 6, 1, 2, 1, 2, 1), v2c.Integer()), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 1), (0,), v2c.Integer(3)), # IF-MIB::ifTable MibTable((1, 3, 6, 1, 2, 1, 2, 2)), MibTableRow((1, 3, 6, 1, 2, 1, 2, 2, 1)).setIndexNames( (0, '__MY_IF_MIB', 'ifIndex')), # IF-MIB::ifIndex MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (1,), v2c.Integer(1)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (2,), v2c.Integer(2)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (3,), v2c.Integer(3)), # IF-MIB::ifDescr MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), v2c.OctetString()), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (1,), v2c.OctetString("lo")), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (2,), v2c.OctetString("eth0")), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (3,), v2c.OctetString("eth1")), # IF-MIB::ifType MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), v2c.Integer()), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (1,), v2c.Integer(24)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (2,), v2c.Integer(6)), MibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (3,), v2c.Integer(6)), # IF-MIB::ifIndex ifIndex=MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), v2c.Integer())) mibBuilder.exportSymbols( '__MY_SNIMPY-MIB', # SNIMPY-MIB::snimpyIpAddress MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 1), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 1), (0,), v2c.OctetString("AAAA")), # SNIMPY-MIB::snimpyString MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 2), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 2), (0,), v2c.OctetString("bye")), # SNIMPY-MIB::snimpyInteger MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 3), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 3), (0,), v2c.Integer(19)), # SNIMPY-MIB::snimpyEnum MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 4), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 4), (0,), v2c.Integer(2)), # SNIMPY-MIB::snimpyObjectId MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 5), v2c.ObjectIdentifier()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 5), ( 0,), v2c.ObjectIdentifier((1, 3, 6, 4454, 0, 0))), # SNIMPY-MIB::snimpyBoolean MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 6), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 6), (0,), v2c.Integer(1)), # SNIMPY-MIB::snimpyCounter MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 7), v2c.Counter32()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 7), (0,), v2c.Counter32(47)), # SNIMPY-MIB::snimpyGauge MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 8), v2c.Gauge32()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 8), (0,), v2c.Gauge32(18)), # SNIMPY-MIB::snimpyTimeticks MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 9), v2c.TimeTicks()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 9), (0,), v2c.TimeTicks(12111100)), # SNIMPY-MIB::snimpyCounter64 MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 10), v2c.Counter64()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 10), (0,), v2c.Counter64(2 ** 48 + 3)), # SNIMPY-MIB::snimpyBits MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 11), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance( (1, 3, 6, 1, 2, 1, 45121, 1, 11), (0,), v2c.OctetString(b"\xa0")), # SNIMPY-MIB::snimpyMacAddress MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 15), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 15), ( 0,), v2c.OctetString(b"\x11\x12\x13\x14\x15\x16")), # SNIMPY-MIB::snimpyIndexTable MibTable((1, 3, 6, 1, 2, 1, 45121, 2, 3)), MibTableRow( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1)).setIndexNames( (0, "__MY_SNIMPY-MIB", "snimpyIndexVarLen"), (0, "__MY_SNIMPY-MIB", "snimpyIndexOidVarLen"), (0, "__MY_SNIMPY-MIB", "snimpyIndexFixedLen"), (1, "__MY_SNIMPY-MIB", "snimpyIndexImplied")), # SNIMPY-MIB::snimpyIndexInt MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row1'), 3, 1, 2, 3, stringToOid('alpha5'), stringToOid('end of row1')), v2c.Integer(4571)), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row2'), 4, 1, 0, 2, 3, stringToOid('beta32'), stringToOid('end of row2')), v2c.Integer(78741)), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row3'), 4, 120, 1, 2, 3, stringToOid('gamma7'), stringToOid('end of row3')), v2c.Integer(4110)), # Indexes snimpyIndexVarLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), v2c.OctetString( )).setMaxAccess("noaccess"), snimpyIndexIntIndex=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 2), v2c.Integer( )).setMaxAccess( "noaccess"), snimpyIndexOidVarLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 3), v2c.ObjectIdentifier( )).setMaxAccess( "noaccess"), snimpyIndexFixedLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 4), v2c.OctetString( ).setFixedLength( 6)).setMaxAccess( "noaccess"), snimpyIndexImplied=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 5), v2c.OctetString( )).setMaxAccess("noaccess"), snimpyIndexInt=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), v2c.Integer()).setMaxAccess("readwrite") ) # Start agent cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) q.put(port) snmpEngine.transportDispatcher.jobStarted(1) snmpEngine.transportDispatcher.runDispatcher()
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')
# SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User(snmpEngine, 'usr-md5-des', config.USM_AUTH_HMAC96_MD5, 'authkey1', config.USM_PRIV_CBC56_DES, 'privkey1') # user: usr-sha-none, auth: SHA, priv NONE config.addV3User(snmpEngine, 'usr-sha-none', config.USM_AUTH_HMAC96_SHA, 'authkey1') # user: usr-sha-none, auth: SHA, priv AES config.addV3User(snmpEngine, 'usr-sha-aes128', config.USM_AUTH_HMAC96_SHA, 'authkey1', config.USM_PRIV_CFB128_AES, 'privkey1') # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, 'usr-sha-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(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(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever
# Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport(snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 1610))) # SNMPv2c setup # SecurityName <-> CommunityName mapping. config.addV1System(snmpEngine, 'my-area', 'public') # Allow read MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 1, 4, 123456789), (1, 3, 6, 1, 4, 123456789)) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # --- define custom SNMP Table within a newly defined EXAMPLE-MIB --- mibBuilder = snmpContext.getMibInstrum().getMibBuilder() (MibTable, MibTableRow, MibTableColumn, MibScalarInstance) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibScalarInstance') RowStatus, = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus')
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)
# Notification targets config.addNotificationTarget( # snmpEngine, 'myNotifyName', 'myParams', 'myManagementStations', 'trap' snmpEngine, 'myNotifyName', 'myParams', 'myManagementStations', 'inform' ) # Setup transport endpoint config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) # Agent-side VACM setup config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 1, 'test-agent', 'noAuthNoPriv', (), (), (1,3,6)) # v1 config.addVacmUser(snmpEngine, 2, 'test-agent', 'noAuthNoPriv', (), (), (1,3,6)) # v2c config.addVacmUser(snmpEngine, 3, 'test-user', 'authPriv', (), (), (1,3,6)) # v3 # SNMP context snmpContext = context.SnmpContext(snmpEngine) def cbFun(snmpEngine, errorIndication, cbCtx): if errorIndication: print errorIndication errorIndication = ntforg.NotificationOriginator(snmpContext).sendNotification( snmpEngine, # Notification targets
#!/usr/bin/env python3 from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asynsock.dgram import udp snmpEngine = engine.SnmpEngine() config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) config.addV1System( snmpEngine, 'c-base', 'public' ) config.addV3User( snmpEngine, 'usr-none-none' ) config.addContest( snmpEngine, '' ) config.addVacmUser( snmpEngine, 1, 'c-base', 'noAuthNoPriv', (1,3,6), (1,3,6) ) config.addVacmUser( snmpEngine, 2, 'c-base', 'noAuthNoPriv', (1,3,6), (1,3,6) ) config.addVacmUser( snmpEngine, 3, 'usr-none-none', 'noAuthNoPriv', (1,3,6), (1,3,6) ) snmpContext = context.snmpContext( snmpEngine ) cmdrsp.GetCommandResponder( snmpEngine, snmpContext ) cmdrsp.SetCommandResponder( snmpEngine, snmpContext ) cmdrsp.NextCommandResponder( snmpEngine, snmpContext ) cmdrsp.BulkCommandResponder( snmpEngine, snmpContext ) snmpEngine.transportDispatcher.jobStarted(1) try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise
config.addV3User( snmpEngine, 'test-user', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' # config.usmAesCfb128Protocol, 'privkey1' ) # Install default Agent configuration #config.setInitialVacmParameters(snmpEngine) # # Apply initial VACM configuration to this user #config.addVacmGroup(snmpEngine, "initial", 3, "test-user") # Alternatively, configure VACM from the scratch config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 1, 'test-agent', 'noAuthNoPriv', (1,3,6), (1,3,6)) # v1 config.addVacmUser(snmpEngine, 2, 'test-agent', 'noAuthNoPriv', (1,3,6), (1,3,6)) # v2c config.addVacmUser(snmpEngine, 3, 'test-user', 'authPriv', (1,3,6), (1,3,6)) # v3 # SNMP context snmpContext = context.SnmpContext(snmpEngine) # Apps registration cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish snmpEngine.transportDispatcher.runDispatcher()
# # Install default Agent configuration # Install default Agent configuration #config.setInitialVacmParameters(snmpEngine) # # Apply initial VACM configuration to this user #config.addVacmGroup(snmpEngine, "initial", 3, "usr-md5-des") # Alternatively, configure VACM from the scratch # default context config.addContext(snmpEngine, '') # allow full MIB access for each user config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (1,3,6), (1,3,6)) config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1,3,6), (1,3,6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1,3,6), (1,3,6)) config.addVacmUser(snmpEngine, 3, 'usr-none-none', 'noAuthNoPriv', (1,3,6), (1,3,6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (1,3,6), (1,3,6)) config.addVacmUser(snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (1,3,6), (1,3,6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-aes256', 'authPriv', (1,3,6), (1,3,6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-aes192', 'authPriv', (1,3,6), (1,3,6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-3des', 'authPriv', (1,3,6), (1,3,6)) # # CommandResponder could serve multiple independent MIB trees # selected by ContextName parameter. The default ContextName is # an empty string, this is where SNMP engine's LCD also lives. # snmpContext = context.SnmpContext(snmpEngine)
# 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 reactor.run()
udp.domainName, ('127.0.0.1', 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', 'trap' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (1), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (), (), (1,3,6)) @trollius.coroutine def snmpOperation(snmpEngine, target, snmpContext, contextName, notificationName, instanceIndex, additionalVarBinds): future = ntforg.NotificationOriginator().sendVarBinds( snmpEngine, target, snmpContext, contextName, notificationName, instanceIndex, additionalVarBinds ) # We know we are sending TRAP which will never produce any response.
config.addTargetAddr(snmpEngine, 'my-nms', udp.domainName, ('127.0.0.1', 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', 'trap') # Allow NOTIFY access to Agent's MIB by this SNMP model (3), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (), (), (1, 3, 6)) # Create default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1, 3, 6, 1, 6, 3, 1, 1, 5, 1), # ( (oid, value), ... )
snmpEngine, transportDomain, udp.UdpTransport().openServerMode(transportAddress) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6), (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) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try:
def __init__(self): #each SNMP-based application has an engine self._snmpEngine = engine.SnmpEngine() # Reading configuration self._read_conf() self._serialtcp = SerialHTTPProcess( self._CONF['LOG_DIR'] if 'LOG_DIR' in self._CONF else '') #open a UDP socket to listen for snmp requests port = int(self._CONF['PORT'] ) if 'PORT' in self._CONF and self._CONF['PORT'] else 161 config.addSocketTransport( self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('0.0.0.0', port))) #add a v2 user with the community string public config.addV1System( self._snmpEngine, "read-area", self._CONF['PUBLIC'] if 'PUBLIC' in self._CONF and self._CONF['PUBLIC'] else "public") config.addV1System( self._snmpEngine, 'write-area', self._CONF['PRIVATE'] if 'PRIVATE' in self._CONF and self._CONF['PRIVATE'] else '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, 1, "read-area", "noAuthNoPriv", readSubTree=(1, 3, 6, 1, 2)) #config.addVacmUser(self._snmpEngine, 1, "read-area", "noAuthNoPriv", # readSubTree=(1, 3, 6, 1, 2, 1, 19, 2, 1)) config.addVacmUser(self._snmpEngine, 1, "read-area", "noAuthNoPriv", readSubTree=(1, 3, 6, 1, 4, 1, 332, 11)) config.addVacmUser(self._snmpEngine, 2, "read-area", "noAuthNoPriv", readSubTree=(1, 3, 6, 1, 2, 1, 10, 33)) config.addVacmUser(self._snmpEngine, 2, "read-area", "noAuthNoPriv", readSubTree=(1, 3, 6, 1, 2, 1, 19, 2, 1)) config.addVacmUser(self._snmpEngine, 2, "read-area", "noAuthNoPriv", readSubTree=(1, 3, 6, 1, 4, 1, 332, 11)) # Write Subtree log('before enable write-area') if self._CONF and 'ALLOW' in self._CONF and self._CONF['ALLOW'].lower( ) in 'true': log('Adding Write community with write-area') config.addVacmUser(self._snmpEngine, 1, 'write-area', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 2, 1, 10, 33), writeSubTree=(1, 3, 6, 1, 2, 1, 10, 33)) config.addVacmUser(self._snmpEngine, 2, 'write-area', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 2, 1, 10, 33), writeSubTree=(1, 3, 6, 1, 2, 1, 10, 33)) config.addVacmUser(self._snmpEngine, 1, 'write-area', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 2, 1, 19, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1, 19, 2, 1)) config.addVacmUser(self._snmpEngine, 2, 'write-area', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 2, 1, 19, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1, 19, 2, 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 #MIBS directory for our new MIB. We'll also use it to #export our symbols later mibBuilder = self._snmpContext.getMibInstrum().getMibBuilder() pub = path.join(getcwd(), 'PYSNMP_MIBS') priv = path.join(getcwd(), 'MIBSPY') mibSources = mibBuilder.getMibSources() + ( builder.DirMibSource(pub), ) + (builder.DirMibSource(priv), ) mibBuilder.setMibSources(*mibSources) #export our custom mib self._exportprivMIBS(mibBuilder) self._exportpubMIBS(mibBuilder) # tell pysnmp to respotd to get, getnext, set and getbulk cmdrsp.GetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.NextCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.SetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.BulkCommandResponder(self._snmpEngine, self._snmpContext)
# Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. config.addV1System(snmpEngine, 'my-area', 'public') # Allow read MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 6), (1, 3, 6, 6)) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # --- define custom SNMP Table within a newly defined EXAMPLE-MIB --- mibBuilder = snmpContext.getMibInstrum().getMibBuilder() (MibTable, MibTableRow, MibTableColumn, MibScalarInstance) = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibTable', 'MibTableRow',
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)
config.USM_PRIV_CBC56_DES, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( snmpEngine, 'usr-sha-none', config.USM_AUTH_HMAC96_SHA, 'authkey1' ) # user: usr-sha-none, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes128', config.USM_AUTH_HMAC96_SHA, 'authkey1', config.USM_PRIV_CFB128_AES, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, 'usr-sha-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(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(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Run Twisted main loop reactor.run()
# 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 reactor.run()
snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport(snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161))) # SNMPv3/USM setup # user: usr-md5-none, auth: MD5, priv NONE config.addV3User(snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1') # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Create an SNMP context with ContextEngineId = 8000000001020304 snmpContext = context.SnmpContext( snmpEngine, contextEngineId=v2c.OctetString(hexValue='8000000001020304')) # Create an [empty] set of Managed Objects (MibBuilder), pass it to # Management Instrumentation Controller and register at SNMP Context # under ContextName 'my-context' snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name instrum.MibInstrumController(builder.MibBuilder()) # Managed Objects ) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext)
def engine(self): """ Setup SNMP engine and context """ log = 'SNMP agent engine initialization sequence begun. ' +\ 'This may take a minute or two.' logger.info(log) print(log) MPQ_ACT.put_nowait([datetime.now().isoformat(' '), 'INFO', log]) # Create SNMP engine with auto generated engineID and pre-bound # to socket transport dispatcher self.eng_snmp = engine.SnmpEngine() # Transport setup # UDP over IPv4 at 0.0.0.0:8900 config.addTransport( self.eng_snmp, udp.domainName, udp.UdpTransport().openServerMode(iface=('', 8900))) # UDP over IPv6 at [::]:8900 config.addTransport( self.eng_snmp, udp6.domainName, udp6.Udp6Transport().openServerMode(iface=('::', 8900))) # SNMPv2c setup # SecurityName <-> CommunityName mapping. config.addV1System(snmpEngine=self.eng_snmp, communityIndex='agent', communityName='janusess') # Allow full MIB access for this user / securityModels at VACM # MIB 1.3.6.1.4.1.9934 refers to Janus Research Group # MIB 1.3.6.1.4.1.9934.0 refers to JanusESS Project config.addVacmUser(snmpEngine=self.eng_snmp, securityModel=2, securityName='agent', securityLevel='noAuthNoPriv', readSubTree=(1, 3, 6, 1, 4, 1, 9934, 0)) # Get default SNMP context this SNMP engine serves self.ctx_snmp = context.SnmpContext(snmpEngine=self.eng_snmp) # Create custom Managed Object Instance self.mib_builder = self.ctx_snmp.getMibInstrum().getMibBuilder() mib_sources = self.mib_builder.getMibSources() + \ ( builder.DirMibSource('/opt/Janus/ESS/python3/server/snmp/mibs'), ) self.mib_builder.setMibSources(*mib_sources) # JANUS-MIB defines and locates all Janus Research Group projects # JANUSESS-MIB defines all JanusESS project entries self.mib_builder.loadModules('JANUS-MIB', 'JANUSESS-MIB') self.config_base() self.config_lane() self.config_module() self.config_sensor() # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(self.eng_snmp, self.ctx_snmp) cmdrsp.NextCommandResponder(self.eng_snmp, self.ctx_snmp) cmdrsp.BulkCommandResponder(self.eng_snmp, self.ctx_snmp) dispatcher = threading.Thread(target=self.dispatcher, args=()) dispatcher.start() MPQ_STAT.put_nowait(['snmp_agent', dispatcher.ident]) log = 'SNMP agent engine sequence concluded.' logger.info(log) MPQ_ACT.put_nowait([datetime.now().isoformat(' '), 'INFO', log]) MPQ_STAT.put_nowait(['base', ['snmp_agent', STAT_LVL['op']]]) log = 'SNMP agent listener started.' logger.info(log) print(log) MPQ_ACT.put_nowait([datetime.now().isoformat(' '), 'INFO', log]) # Poll SNMP agent queues for values to update variables while True: if not MPQ_SNMPA_STOP.empty(): MPQ_SNMPA_STOP.get() self.eng_snmp.transportDispatcher.closeDispatcher() break if not MPQ_SNMPA2.empty(): mpq_record = MPQ_SNMPA2.get() self.base(mpq_record=mpq_record) if not MPQ_SNMPA3.empty(): mpq_record = MPQ_SNMPA3.get() self.lane(mpq_record=mpq_record) if not MPQ_SNMPA4.empty(): mpq_record = MPQ_SNMPA4.get() self.module(mpq_record=mpq_record) if not MPQ_SNMPA5.empty(): mpq_record = MPQ_SNMPA5.get() self.sensor(mpq_record=mpq_record) time.sleep(0.1) MPQ_STAT.put_nowait(['snmp_agent', False]) log = 'SNMP agent dispatcher stopped.' logger.info(log) MPQ_ACT.put_nowait([datetime.now().isoformat(' '), 'INFO', log]) log = 'SNMP agent listener stopped.' logger.info(log) print(log) MPQ_ACT.put_nowait([datetime.now().isoformat(' '), 'INFO', log]) MPQ_STAT.put_nowait(['base', ['snmp_agent', STAT_LVL['not_cfg']]])