def __init__(self, hostname, community="public"): self.hostname = hostname self.community = community mib_builder = builder.MibBuilder() mib_builder.setMibPath(*(mib_builder.getMibPath() + (sys.path[0], ))) mib_builder.loadModules('RFC1213-MIB', 'BRIDGE-MIB', 'IF-MIB', 'Q-BRIDGE-MIB', 'IP-MIB', 'HP-ICF-IPCONFIG') self.mib_view_controller = view.MibViewController(mib_builder) self.command_generator = cmdgen.CommandGenerator() self.command_generator.mibViewController = view.MibViewController( mib_builder)
def consultaSNMP(comunidad,host,oid): mibBuilder = builder.MibBuilder() mibViewController = view.MibViewController(mibBuilder) compiler.addMibCompiler(mibBuilder, sources=['file:///usr/local/lib/python2.7/dist-packages/pysnmp/smi/mibs', 'http://mibs.snmplabs.com/asn1/@mib@']) mibBuilder.loadModules('RFC1213-MIB','IF-MIB') objectIdentity = rfc1902.ObjectIdentity(oid).resolveWithMib(mibViewController) errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(comunidad), UdpTransportTarget((host, 161)), ContextData(), #ObjectType(ObjectIdentity(oid)))) ObjectType( objectIdentity ))) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(),errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: varB=(' = '.join([x.prettyPrint() for x in varBind])) resultado= " ".join(varB.split()[2:]) return resultado
def __init__(self, host, public, private, port=161, timeout=1, retries=2): """Create the snmpy object. :param host: hostname or IP address of the device to communicate with :type host: str :param public: public community string :type public: str :param private: private community string :type private: str :param port: port number to connect on (default 161) :type port: int :param timeout: timeout, in seconds (default 1s) :type timeout: int :param retries: number of retries (default 2) :type retries: int :returns: new Snmpy object :rtype: Snmpy """ self._host = host self._port = port self._timeout = timeout self._retries = retries self._transport = cmdgen.UdpTransportTarget((self._host, self._port), timeout=self._timeout, retries=self._retries) self._public = cmdgen.CommunityData(public, mpModel=self.VERSION_2_2C) self._private = cmdgen.CommunityData(private, mpModel=self.VERSION_2_2C) self._mib_builder = builder.MibBuilder() self._mib_view_controller = view.MibViewController(self._mib_builder) # Pre-load some commonly used modules. self.load_mibs('SNMPv2-MIB', 'IF-MIB', 'IP-MIB', 'HOST-RESOURCES-MIB', 'FIBRE-CHANNEL-FE-MIB')
def checkSNMP(community, host, port, oid): mibBuilder = builder.MibBuilder() mibViewController = view.MibViewController(mibBuilder) compiler.addMibCompiler(mibBuilder, sources=['http://mibs.snmplabs.com/asn1/@mib@']) mibBuilder.loadModules('RFC1213-MIB', 'IF-MIB') objectIdentity = rfc1902.ObjectIdentity(oid).resolveWithMib( mibViewController) errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(community), UdpTransportTarget((host, port), timeout=1.5, retries=0), ContextData(), ObjectType(objectIdentity))) if errorIndication: print(errorIndication, " : ", host) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: varB = (' = '.join([x.prettyPrint() for x in varBind])) resultado = " ".join(varB.split()[2:]) return resultado return -1
def generator(cbCtx, ast): snmpEngine, ctx = cbCtx ctx['mibViewController'] = view.MibViewController( snmpEngine.getMibBuilder()) return _MainGenerator().preorder((snmpEngine, ctx), ast)
def getMibViewController(self, snmpEngine): mibViewController = snmpEngine.getUserContext('mibViewController') if not mibViewController: mibViewController = view.MibViewController( snmpEngine.getMibBuilder()) snmpEngine.setUserContext(mibViewController=mibViewController) return mibViewController
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): try: #Enables pysmi debugging #debug.setLogger(debug.Debug('reader')) # Assemble MIB viewer mibBuilder = builder.MibBuilder() mibViewController = view.MibViewController(mibBuilder) # Pre-load MIB modules we expect to work with try: mibBuilder.loadModules('SNMPv2-MIB') except: logging.error("Fail loading mibs") # vars to store, match here the MIB field you need to save # cLApName = '1.3.6.1.4.1.9.9.513.1.1.1.1.5.0' # cLApRogueApMacAddress = '1.3.6.1.4.1.9.9.513.3.2.0' # cLApDot11IfType = '1.3.6.1.4.1.9.9.513.1.2.1.1.2.0' while wholeMsg: msgVer = int(api.decodeMessageVersion(wholeMsg)) if msgVer in api.protoModules: pMod = api.protoModules[msgVer] else: print('Unsupported SNMP version %s' % msgVer) logging.error('Unsupported SNMP version %s' % msgVer) return reqMsg, wholeMsg = decoder.decode( wholeMsg, asn1Spec=pMod.Message(), ) print('Notification message from %s:%s: ' % (transportDomain, transportAddress)) logging.info('Notification message from %s:%s: ' % (transportDomain, transportAddress)) reqPDU = pMod.apiMessage.getPDU(reqMsg) if reqPDU.isSameTypeWith(pMod.TrapPDU()): if msgVer == api.protoVersion1: varBinds = pMod.apiTrapPDU.getVarBinds(reqPDU) else: varBinds = pMod.apiPDU.getVarBinds(reqPDU) print('Var-binds:') logging.info( '--------------------------------------------------------------------' ) logging.info('Var-binds:') trap = TrapEvent() for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) trap.sender = str(transportAddress[0]) # trap.persistToDB() return wholeMsg except Exception as e: trap = TrapEvent() logging.error(str(e)) trap.persistLogToDB(str(e))
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 _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 __init__(self, args): configDict = loadConfig(args.config) self.moduleLogger = set_logging(configDict, __class__.__name__) self.moduleLogger.debug('configDict:{}'.format(configDict)) mibBuilder = builder.MibBuilder() self._mibViewController = view.MibViewController(mibBuilder) compiler.addMibCompiler( mibBuilder, sources=configDict['snmp'].get('mibs', ())) # this dict holds all OID items indexed by MIB symbols self._mibObjects = collections.defaultdict(dict) # this dict holds only recently updated OIDs (indexed by # MIB name and object) self._candidateMibObjects = collections.defaultdict(dict) # this dict holds all OID items populated from `mibObjects` self._oids = {} self._expireBy = time.time() + self.EXPIRE_PERIOD self._dirty = True # OIDs need sorting
def set_by_name(self, obj_name, value, idx=(0, )): """Does a SNMP SET request. See `Get` for more information on possible OID notations. Automatic converting to the SNMP type expected by the remote system is only supported for OIDs for which there is a MIB describing it. If you want to use an OID which is not described by a MIB, you'll have to use the `Set XXX`-keyword or `Convert To XXX`-keyword. The optional `idx` is appended to the OID (defaults to `.0`). Example: | Set | SNMPv2::sysDescr | New System Description | """ if self._active_connection is None: raise RuntimeError('No transport host set') mibViewCtl = view.MibViewController(self._active_connection.builder) objIdentity = ObjectIdentity(self.DTM_MIB_LIB_NAME, obj_name) objIdentity.resolveWithMib(mibViewCtl) oid = '.' + str(objIdentity.getOid()) idx = utils.parse_idx(idx) oid = utils.parse_oid(oid) + idx self._set((oid, value))
def translate_mib(custom_mib_paths, load_mib_modules, name, val): """ Translate OID to MIB custom_mib_paths: comma separated mib paths as a string load_mib_modules: MIB Module to load e.g. "MIB-FILE-1,MIB-FILE-2" Return: Translated OID string and value """ if custom_mib_paths and load_mib_modules: try: mibBuilder = builder.MibBuilder() compiler.addMibCompiler(mibBuilder, sources=custom_mib_paths) mibViewController = view.MibViewController(mibBuilder) temp_load_mib_modules = load_mib_modules.split(',') mibBuilder.loadModules(*temp_load_mib_modules) except error.MibNotFoundError as excep: testcase_Utils.pNote(" {} Mib Not Found!".format(excep), "Error") temp_type = val.__class__.__name__ if custom_mib_paths and load_mib_modules: output = rfc1902.ObjectType(rfc1902.ObjectIdentity(name), val).resolveWithMib(mibViewController).prettyPrint() op_list = output.split(" = ") name = op_list[0].strip() t_val = op_list[1].strip() if temp_type == "Integer": testcase_Utils.pNote('%s = %s(%s): %s' % (name, temp_type, val.prettyPrint(), t_val)) else: if t_val == '': #For empty String testcase_Utils.pNote('%s = %s: ""' % (name, temp_type)) else: testcase_Utils.pNote('%s = %s: %s' % (name, temp_type, t_val)) return name, t_val else: testcase_Utils.pNote('%s = %s: %s' % (name.prettyPrint(), temp_type, val.prettyPrint())) return name.prettyPrint(), val.prettyPrint()
def listen( address=DEFAULT_ADDRESSS, port=DEFAULT_PORT, community=DEFAULT_COMMUNITY, mibs=DEFAULT_MIBS, ): """Listen to and SNMP trap and print events.""" # Based on pySNMP example code. mib_builder = builder.MibBuilder() compiler.addMibCompiler(mib_builder) mib_builder.loadModules(*mibs) global _view_controller _view_controller = view.MibViewController(mib_builder) loop = asyncio.get_event_loop() snmp_engine = engine.SnmpEngine() print(f"Agent is listening SNMP Trap on {address}, Port: {port}") if port < 1024: print( "WARNING: Port < 1024. Root priviledges or authbind required on *nix systems." ) print("-" * 79) config.addTransport( snmp_engine, udp.domainName + (1, ), udp.UdpTransport().openServerMode((address, port)), ) config.addV1System(snmp_engine, community, community) ntfrcv.NotificationReceiver(snmp_engine, _listen_callback) print("Press CTRL-C to quit.") loop.run_forever()
def 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 getMibViewController(userCache): try: mibViewController = userCache['mibViewController'] except KeyError: mibViewController = view.MibViewController(builder.MibBuilder()) userCache['mibViewController'] = mibViewController return mibViewController
def __init__(self, targets): self.requests = [] self.targets = targets self.results = [] self.community_string = get_config('snmp')['COMM_STRING'] self.timeout = get_config('snmp')['TIMEOUT'] self.snmpEngine = SnmpEngine() self.mibBuilder = self.snmpEngine.getMibBuilder() self.mibViewController = view.MibViewController(self.mibBuilder) self.loop = asyncio.get_event_loop()
def __init__(self, snmpEngine=None): if snmpEngine is None: self.snmpEngine = engine.SnmpEngine() else: self.snmpEngine = snmpEngine self.mibViewController = view.MibViewController( self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder) self.__knownAuths = {} self.__knownTransports = {} self.__knownTransportAddrs = {}
def get_oid_by_name(self, *names): """get oid from custom names. """ if len(names): self._info('get_oid_by_name %s' % ' '.join(list(names))) mibViewCtl = view.MibViewController( self._active_connection.builder) objIdentity = ObjectIdentity(*names) objIdentity.resolveWithMib(mibViewCtl) return '.' + str(objIdentity.getOid())
def __init__(self, **kwargs): self.standard_mibs = [] self.mongo_client = pymongo.MongoClient(MONGO_URI) if kwargs.get("no_mongo"): self.session = Session() else: self.session = CachedLimiterSession( per_second=120, cache_name="cache_http", backend=MongoCache(connection=self.mongo_client, db_name=MONGO_DB), expire_after=1800, match_headers=False, stale_if_error=True, allowable_codes=[200], ) self.profiles = load_profiles() self.last_modified = time.time() self.snmpEngine = SnmpEngine() self.builder = self.snmpEngine.getMibBuilder() self.mib_view_controller = view.MibViewController(self.builder) compiler.addMibCompiler(self.builder, sources=[MIB_SOURCES]) # mib_standard_response = self.session.get(f"{MIB_STANDARD}", stream=True) # if mib_standard_response.status_code == 200: # for line in mib_standard_response.iter_lines(): # if line: # mib = line.decode("utf-8") # logger.info(f"MIB: {mib}") # try: # self.builder.loadModules(mib) # self.standard_mibs.append(mib) # except Exception as e: # logger.warning(f"An error occurred during loading MIB module: {mib}: {e}") # else: for mib in DEFAULT_STANDARD_MIBS: self.standard_mibs.append(mib) self.builder.loadModules(mib) mib_response = self.session.get(f"{MIB_INDEX}") self.mib_map = {} if mib_response.status_code == 200: with StringIO(mib_response.text) as index_csv: reader = csv.reader(index_csv) for each_row in reader: if len(each_row) == 2: self.mib_map[each_row[1]] = each_row[0] logger.debug(f"Loaded {len(self.mib_map.keys())} mib map entries") else: logger.error( f"Unable to load mib map from index http error {self.mib_response.status_code}" )
def get_value_by_name2(self, idx, *names): """get value from custom names direcly. """ if len(names): self._info('get_oid_by_name %s' % ' '.join(list(names))) mibViewCtl = view.MibViewController( self._active_connection.builder) objIdentity = ObjectIdentity(*names) objIdentity.resolveWithMib(mibViewCtl) oid = '.' + str(idx) + '.' + str(objIdentity.getOid()) return self._get(oid)
def _getCmdCache(self, snmpEngine): if 'cmdgen' not in snmpEngine.cache: snmpEngine.cache['cmdgen'] = { 'auth': {}, 'parm': {}, 'tran': {}, 'addr': {}, } if 'mibViewController' not in snmpEngine.cache['cmdgen']: snmpEngine.cache['cmdgen']['mibViewController'] = view.MibViewController(snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder) return snmpEngine.cache['cmdgen']
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 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 mib_builder(custom_mib_path, LOAD_MIB_MODULE): mibBuilder = builder.MibBuilder() try: if custom_mib_path: compiler.addMibCompiler(mibBuilder, sources=custom_mib_path.split( ",")) global mibViewController mibViewController = view.MibViewController(mibBuilder) if LOAD_MIB_MODULE: _mibs=LOAD_MIB_MODULE.split(",") mibBuilder.loadModules(*_mibs) except error.MibNotFoundError as excep: print(" {} Mib Not Found!".format(excep))
def start(self): self.__lock.acquire() try: self.__mib_builder = builder.MibBuilder() self.__mib_view = view.MibViewController(self.__mib_builder) finally: self.__lock.release() # Load some common MIBs: self.load_mib('SNMP-COMMUNITY-MIB') self.load_mib('SNMP-VIEW-BASED-ACM-MIB') self.load_mib('IF-MIB') super(SNMP, self).start() return
def main(): # Instantiate snmp engine snmpEngine = engine.SnmpEngine() # Load MIBs (for translation of the numeric OIDs) mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB') mibViewController = view.MibViewController(mibBuilder) # Transport setup # UDP over IPv6, listening interface/port config.addTransport( snmpEngine, udp6.domainName + (1,), udp6.Udp6Transport().openServerMode(('::', TRAP_PORT)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): # Translate numerical OIDs into human readable form varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds] # Turn on write permission for everyone os.umask(0) # Open file, append new data at the end with open(os.open(TRAP_LOG_PATH, os.O_CREAT | os.O_WRONLY, 0o777), 'a+') as f: t = time.gmtime() f.write('TRAP received on %s from ContextEngineId "%s", ContextName "%s" \n' % (time.strftime('%c', t), contextEngineId.prettyPrint(), contextName.prettyPrint())) # Write data in file for varbind in varBinds: f.write(varbind.prettyPrint()+'\n') f.write('\n') # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # Start a job that will never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise
def get_first_node_name(mib_filepath, mib_filename): """ Get the node name from the given mib file path and file name :param mib_filepath: Mib file path of the git url or abs file path :param mib_filename: MIB file name :return: oid, lable, suffix, mibView, mibBuilder """ mibBuilder = builder.MibBuilder() compiler.addMibCompiler(mibBuilder, sources=mib_filepath.split(",")) for mib in mib_filename.split(","): mibBuilder.loadModules(mib) mibView = view.MibViewController(mibBuilder) oid, label, suffix = mibView.getFirstNodeName() return oid, label, suffix, mibView, mibBuilder
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 _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 getMIBViewer(): # Create MIB loader/builder mibBuilder = builder.MibBuilder() # log.info('Loading MIB modules...') # mibBuilder.loadModules( # 'SNMPv2-MIB', 'SNMP-FRAMEWORK-MIB', 'SNMP-COMMUNITY-MIB', "IF-MIB" # ) # log.info('done') log.info('Indexing MIB objects...') mibView = view.MibViewController(mibBuilder) log.info('done') return mibView