def update_mib_sources(self, mib_folder_path): """Add specified path to the Pysnmp mib sources, which will be used to translate snmp responses. :param mib_folder_path: string path """ builder.DirMibSource(mib_folder_path) mib_sources = self.mib_builder.getMibSources() + (builder.DirMibSource(mib_folder_path),) self.mib_builder.setMibSources(*mib_sources)
def add_mib_folder_path(self, path): """Add specified path to the Pysnmp mib sources. They will be used to translate snmp responses. :param path: string path to mibs """ mib_builder = self._snmp_engine.msgAndPduDsp.mibInstrumController.mibBuilder builder.DirMibSource(path) mib_sources = ( builder.DirMibSource(path), ) + mib_builder.getMibSources() mib_builder.setMibSources(*mib_sources)
def _setup(self): """ Setup Server """ assert isinstance(self._callbacks, list), \ "callbacks should be list of functions type not %s" % type( self._callbacks) snmp_engine = engine.SnmpEngine() build = snmp_engine.getMibBuilder() if self._add_mib_dir: if not os.path.exists(self._add_mib_dir): raise PiatError("mib dir does not exist, dir=%r" % self._add_mib_dir) if not os.path.isdir(self._add_mib_dir): raise PiatError( "add_mib_dir should be a directory not a file, add_mib_dir=%r" % self._add_mib_dir) build.addMibSources(builder.DirMibSource(self._add_mib_dir)) build.loadModules() viewer = view.MibViewController(build) # UDP over IPv4, first listening interface/port transport = udp.UdpTransport() config.addTransport(snmp_engine, udp.domainName + (1, ), transport.openServerMode(('0.0.0.0', self._port))) # SecurityName <-> CommunityName mapping config.addV1System(snmp_engine, '????', self._community) # Register SNMP Application at the SNMP engine handler = TrapsHandler(self._callbacks, viewer) ntfrcv.NotificationReceiver(snmp_engine, handler.handle) self._snmpEngine = snmp_engine
def add_mib_path(self, path): """Add an additional directory to the MIB search path. :param path: path to additional MIBs """ mib_path = normpath(path) self._mib_builder.addMibSources(builder.DirMibSource(mib_path))
def __init__(self, ip, port=161, snmp_version='', snmp_community='', snmp_user='', snmp_password='', snmp_private_key='', auth_protocol=usmHMACSHAAuthProtocol, private_key_protocol=usmDESPrivProtocol, logger=None, snmp_errors=list()): """ Initialize SNMP environment . :param ip: target device ip address :param port: snmp port :param snmp_version: snmp version, i.e. v2c, v3, etc. :param snmp_community: snmp community name, used to instantiate snmp agent version 2 :param snmp_user: snmp user name, used to instantiate snmp agent version 3 :param snmp_password: snmp password, used to instantiate snmp agent version 3 :param snmp_private_key: snmp private key, used to instantiate snmp agent version 3 :param auth_protocol: authentication protocol, used to instantiate snmp agent version 3, i.e. usmNoAuthProtocol, usmHMACMD5AuthProtocol, etc. objects :param private_key_protocol: private key protocol, used to instantiate snmp agent version 3, i.e. usmNoPrivProtocol, usm3DESEDEPrivProtocol, usmAesCfb128Protocol, etc. objects """ self.cmd_gen = cmdgen.CommandGenerator() self.mib_builder = self.cmd_gen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder self.mib_viewer = view.MibViewController(self.mib_builder) self.mib_path = builder.DirMibSource(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mibs')) self._logger = logger self.target = None self.security = None self._snmp_errors = {pattern: re.compile(pattern, re.IGNORECASE) for pattern in snmp_errors} self.initialize_snmp(ip, port, snmp_version, snmp_community, snmp_user, snmp_password, snmp_private_key, auth_protocol, private_key_protocol) self.mib_builder.setMibSources(self.mib_path)
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 create_managed_objects(self): builder = self.context.getMibInstrum().getMibBuilder() # Add Unity-MIB.py to mib source dir mib_dir_path = os.path.join(os.path.dirname(__file__), 'mibs') builder.setMibSources( snmp_builder.DirMibSource(mib_dir_path), *builder.getMibSources()) mib_scalar, mib_table_column, mib_table_row, mib_scalar_instance = ( builder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTableColumn', 'MibTableRow', 'MibScalarInstance')) module_name = "Unity-MIB" instances = [] table_rows = [] mib_symbols = [item[0] for item in mib_parser.get_mib_symbols(module_name)] mib_objects = builder.importSymbols(module_name, *mib_symbols) for item in mib_objects: if isinstance(item, mib_table_row): table_rows.append(item) for item in mib_objects: class_name = item.label[:1].upper() + item.label[1:] try: mod = __import__("snmpagent_unity.unity_impl." + class_name, fromlist=[item.label]) except ImportError: continue if isinstance(item, mib_table_column): entry = None for row in table_rows: if row.getName() == item.getName()[:-1]: entry = row scalar_instance_clz = factory.ScalarInstanceFactory.build( class_name, base_class=mib_scalar_instance, impl_class=getattr(mod, class_name)) column_instance_clz = factory.TableColumnInstanceFactory.build( class_name, base_class=mib_table_column, proto_inst=scalar_instance_clz, entry=entry, impl_class=getattr(mod, class_name + "Column")) instances.append(column_instance_clz(item.name, item.syntax)) elif isinstance(item, mib_scalar): scalar_instance_clz = factory.ScalarInstanceFactory.build( class_name, base_class=mib_scalar_instance, impl_class=getattr(mod, class_name)) instances.append(scalar_instance_clz(item.name, (0,), item.syntax)) builder.exportSymbols('Exported-Unity-MIB', *instances)
def init_mib_builder(self): #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 self.mibBuilder = self._snmpContext.getMibInstrum().getMibBuilder() mibSources = self.mibBuilder.getMibSources() + (builder.DirMibSource('./mibpy'),) self.mibBuilder.setMibSources(*mibSources) self.mibViewController = view.MibViewController(self.mibBuilder)
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 create_command_generator(self, mibs_path, ignore_nonincreasing_oid): cmd_generator = cmdgen.CommandGenerator() cmd_generator.ignoreNonIncreasingOid = ignore_nonincreasing_oid if mibs_path is not None: mib_builder = cmd_generator.snmpEngine.msgAndPduDsp. \ mibInstrumController.mibBuilder mib_sources = mib_builder.getMibSources() + \ (builder.DirMibSource(mibs_path),) mib_builder.setMibSources(*mib_sources) return cmd_generator
def add_mib_path(path): """Add a directory to the MIB search path""" if not os.path.isdir(path): return for source in __mibBuilder.getMibSources(): if isinstance(source, builder.DirMibSource): if source.fullPath() == path: return __mibBuilder.setMibSources(*(__mibBuilder.getMibSources() + (builder.DirMibSource(path), )))
def set_mib_mibsources(self, mibs, mibSources): # logger.warning("[SnmpPoller] set_mib_mibsources %s %s", mibs, mibSources) self.mibs = mibs self.mibSources = mibSources self.mibBuilder = builder.MibBuilder() extraMibSources = tuple( [builder.DirMibSource(d) for d in self.mibSources]) totalMibSources = extraMibSources + self.mibBuilder.getMibSources() self.mibBuilder.setMibSources(*totalMibSources) if self.mibs: self.mibBuilder.loadModules(*self.mibs) self.mibViewController = view.MibViewController(self.mibBuilder)
def create_command_generator(cls, mibs_path=None): ''' Create a command generator to perform all the snmp query. If mibs_path is not None, load the mibs present in the custom mibs folder. (Need to be in pysnmp format) ''' cls.cmd_generator = cmdgen.CommandGenerator() if mibs_path is not None: mib_builder = cls.cmd_generator.snmpEngine.msgAndPduDsp.\ mibInstrumController.mibBuilder mib_sources = mib_builder.getMibSources() + ( builder.DirMibSource(mibs_path), ) mib_builder.setMibSources(*mib_sources)
def add_personal_mib(self): ''' 增加LIB的方法,写的很详细,角本中的BUILD和例子中的有区别,注意库的引用有所不同 https://programtalk.com/vs2/python/11801/sd-agent/checks.d/snmp.py/ ''' mibs_path = 'C:\\robot\\' # print mibs_path if mibs_path: mib_sources = self.build.getMibSources() + (builder.DirMibSource(mibs_path),) # print "mib_sources: ", mib_sources self.build.setMibSources(*mib_sources) for mib_path in self.build.getMibSources(): logging.warning("mibsource add path: {}".format(mib_path))
def _load_pysnmp_modules(cmd_gen, mibs_directory=None): mib_builder = cmd_gen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder unit_mib_path = _dir_mib_source if mibs_directory == None else mibs_directory # override default _pysnmp Library unit_mib_source = builder.DirMibSource(_find_pysnmp_dir(unit_mib_path)) # mib_sources = mib_builder.getMibSources() + (_dir_mib_source,) mib_sources = mib_builder.getMibSources() + (unit_mib_source, ) mib_builder.setMibSources(*mib_sources) mib_builder.loadModules(*MIBS.values())
def _mib_builder(self): """Loads given set of mib files from given path.""" mib_builder = builder.MibBuilder() try: self.mib_view_controller = view.MibViewController(mib_builder) # set mib path to mib_builder object and load mibs mib_path = builder.DirMibSource(self.snmp_mib_path), mib_builder.setMibSources(*mib_path) if len(MIB_LOAD_LIST) > 0: mib_builder.loadModules(*MIB_LOAD_LIST) except Exception: raise ValueError("Mib load failed.")
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)
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 create_snmp_engine(mibs_path): """ Create a command generator to perform all the snmp query. If mibs_path is not None, load the mibs present in the custom mibs folder. (Need to be in pysnmp format) """ snmp_engine = hlapi.SnmpEngine() mib_builder = snmp_engine.getMibBuilder() if mibs_path is not None: mib_builder.addMibSources(builder.DirMibSource(mibs_path)) mib_view_controller = view.MibViewController(mib_builder) return snmp_engine, mib_view_controller
def get_cmd_gen(mib_names_args): global mib_view # load in custom MIBS cmd_gen = cmdgen.CommandGenerator() mib_builder = cmd_gen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder mib_sources = (builder.DirMibSource(mib_egg_dir), ) for mibfile in os.listdir(mib_egg_dir): if mibfile.endswith(".egg"): mib_sources = mib_sources + (builder.ZipMibSource(mibfile), ) mib_sources = mib_builder.getMibSources() + mib_sources mib_builder.setMibSources(*mib_sources) if mib_names_args: mib_builder.loadModules(*mib_names_args) mib_view = view.MibViewController(mib_builder) return cmd_gen, mib_view
def _mib_builder(self): """Loads the MIB files and creates dicts with hierarchical structure""" # Create MIB loader/builder mibBuilder = builder.MibBuilder() self._log_debug('Reading MIB sources...') mibSources = mibBuilder.getMibSources() + ( builder.DirMibSource('/etc/sspl-ll/templates/snmp'), ) mibBuilder.setMibSources(*mibSources) self._log_debug("MIB sources: %s" % str(mibBuilder.getMibSources())) for module in self._enabled_MIBS: mibBuilder.loadModules(module) self._mibView = view.MibViewController(mibBuilder)
def create_command_generator(self, mibs_path, ignore_nonincreasing_oid): ''' Create a command generator to perform all the snmp query. If mibs_path is not None, load the mibs present in the custom mibs folder. (Need to be in pysnmp format) ''' cmd_generator = cmdgen.CommandGenerator() cmd_generator.ignoreNonIncreasingOid = ignore_nonincreasing_oid if mibs_path is not None: mib_builder = cmd_generator.snmpEngine.msgAndPduDsp.\ mibInstrumController.mibBuilder mib_sources = mib_builder.getMibSources() + \ (builder.DirMibSource(mibs_path), ) mib_builder.setMibSources(*mib_sources) return cmd_generator
def _get_mib_viewer(cmdGen): ''' The mibBuilder.loadModules() can be used to load mib modules that can be used for mib lookup. # Currently the lookup has been disabled. ''' mibBuilder = cmdGen.mibViewController.mibBuilder for path in mib_dir.split(":"): mibPath = mibBuilder.getMibSources() + \ (builder.DirMibSource(str(path)),) mibBuilder.setMibSources(*mibPath) for module in _get_mib_modules(): try: mibBuilder.loadModules(module) except SmiError, msg: logging.warn("Error loading mib module (%s), error=(%s)", module, msg) pass
def _mib_builder(self): """Loads given set of mib files from given path.""" mib_builder = builder.MibBuilder() try: self.mib_view_controller = view.MibViewController(mib_builder) # Append custom mib path to default path for loading mibs mib_sources = mib_builder.getMibSources() + (builder.DirMibSource( self.snmp_mib_path),) mib_builder.setMibSources(*mib_sources) files = [] for file in os.listdir(self.snmp_mib_path): # Pick up all .py files, remove extenstion and load them if file.endswith(MIB_LOAD_FILE_FORMAT): files.append(os.path.splitext(file)[0]) if len(files) > 0: mib_builder.loadModules(*files) except Exception: raise ValueError("Mib load failed.")
def __init__(self, snmp_parameters, logger, snmp_error_values=None): """ Initialize SNMP environment. :param SNMPParameters snmp_parameters: snmp parameters """ self._snmp_errors = None snmp_error_values = snmp_error_values or [] self.set_snmp_errors(snmp_error_values) self.cmd_gen = cmdgen.CommandGenerator() self.mib_builder = self.cmd_gen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder self.mib_viewer = view.MibViewController(self.mib_builder) self.mib_path = builder.DirMibSource( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mibs')) self.logger = logger self.is_read_only = False self.target = None self.security = None self.initialize_snmp(snmp_parameters) self.mib_builder.setMibSources(self.mib_path)
def mibTextToPy(mib_path): """ Convert mibs to a format that pysnmp can actually use. """ logging.info("Setting MIB Path") cmdGen = cmdgen.CommandGenerator() mibBuilder = builder.MibBuilder() mibBuilder = cmdGen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder mibSources = mibBuilder.getMibSources() + (builder.DirMibSource(mib_path), ) mibBuilder.setMibSources(*mibSources) logging.info(mibBuilder.getMibSources()) if os.path.isdir(mib_path): for mib in MIB_SRCLIST: mib_preload = mib[0] mib_srcname = mib[1] mib_destname = mib[2] if not os.path.isfile(os.path.join(mib_path, mib_srcname)): logging.critical("FAILED: Required MIB %s is missing from \ path %s") % (mib_srcname, mib_path) return 1 logging.info("Converting MIB to py") if mib_preload: cmd = "smidump -k -p %s -f python %s | libsmi2pysnmp > %s" % \ (os.path.join(mib_path, mib_preload), os.path.join(mib_path, mib_srcname), os.path.join(mib_path, mib_destname) + ".py") else: cmd = "smidump -k -f python %s | libsmi2pysnmp > %s" % \ (os.path.join(mib_path, mib_srcname), os.path.join(mib_path, mib_destname) + ".py") logging.info(cmd) os.system(cmd) logging.info("Loading MIB") mibBuilder.loadModules(mib_destname) logging.info(mib_destname) else: logging.critical("FAILED: MIB directory %s is not present") % mib_path return 1 return cmdGen
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): self._snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping config.addV1System(self._snmpEngine, 'my-area', self.community) # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(self._snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # # Setup transport endpoint and bind it with security settings yielding # a target name (choose one entry depending of the transport needed). # # UDP/IPv4 config.addSocketTransport( self._snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( self._snmpEngine, 'my-router', udp.domainName, (self.host, self.port), 'my-creds' ) self.mibBuilder = builder.MibBuilder() self.mibSources logger.info("[SNMP] client %s: %s / %s", self, self.mibSources, self.mibs) extraMibSources = tuple([builder.DirMibSource(d) for d in self.mibSources]) totalMibSources = extraMibSources + self.mibBuilder.getMibSources() self.mibBuilder.setMibSources(*totalMibSources) if self.mibs: self.mibBuilder.loadModules(*self.mibs) self.mibViewController = view.MibViewController(self.mibBuilder) self.auth_data = cmdgen.CommunityData('krill', self.community, self.version - 1) self.udp_transport_target = cmdgen.UdpTransportTarget( (self.host, self.port), timeout=self.timeout, retries=self.retries)
def _make_mib_sources(self, mib_builder): return mib_builder.getMibSources() + (builder.DirMibSource( self.directory), )
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)