def get_table_oids(target, oids, credentials, start_from=0, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): """ Send a get SNMP request for a table request inputs: target (str) : Device IP address oids (list) : List of oids (e.g (['.1.1.2.4.5', '.1.1.2.4.7')) credentials (str) : SNMP Community outputs: SNMP response (dict) """ ObjectList = list() for oid in oids : ObjectList.append(ObjectType(ObjectIdentity(oid))) handler = hlapi.nextCmd( engine, credentials, hlapi.UdpTransportTarget((target, port),timeout=10), context, *ObjectList, lexicographicMode=False ) if len(oids) > 1 : return cut_array_to_table(fetch(handler),len(oids)) else : return fetch(handler)
def get_table(target, oids, credentials, start_from=0, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): """ Send a get SNMP request for a table request inputs: target (str) : Device IP address oids (list) : List of unindexed MIB entries (e.g ('IF-MIB', 'ifDescr')) credentials (str) : SNMP Community outputs: SNMP response (dict) """ handler = hlapi.nextCmd( engine, credentials, hlapi.UdpTransportTarget((target, port),timeout=10), context, *construct_object_types_from_named_oid(oids), lexicographicMode=False ) if len(oids) > 1 : return cut_array_to_table(fetch(handler),len(oids)) else : return fetch(handler)
def snmpWalk(snmpVersion, community, host, port, oid): logging.info('New Walk Query [v:%d, %s, %s, %d, %s]', snmpVersion, community, host, port, oid) generator = snmp.nextCmd(snmp.SnmpEngine(), snmp.CommunityData(community, mpModel=snmpVersion), snmp.UdpTransportTarget((host, port)), snmp.ContextData(), snmp.ObjectType(snmp.ObjectIdentity(oid)), lexicographicMode=False) results = dict() for errorIndication, errorStatus, errorIndex, varBinds in generator: if errorIndication: logging.error(errorIndication) raise Exception('SnmpWalk ErrorIndication.') if errorStatus: logging.error( '%s at %s', errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?') raise Exception('SnmpWalk ErrorStatus.') for name, value in varBinds: results[str(name)] = str(value) return results
def _snmp_walk(host, community, oid): assert host, "host must be defined." assert community, "community must be defined." assert oid, "oid must be defined." assert isinstance(oid, ObjectType), "oid must be of ObjectType" for errorIndication, errorStatus, errorIndex, varBinds in nextCmd( SnmpEngine(), CommunityData(community, mpModel=1), UdpTransportTarget((host, 161)), ContextData(), oid, ignoreNonIncreasingOid=True, lookupMib=True, lexicographicMode=False): if errorIndication: logger.error(errorIndication) else: if errorStatus: raise Exception('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for name, val in varBinds: yield name.prettyPrint(), val.prettyPrint()
def walk(target, oid, credentials,table): port=161 engine=hlapi.SnmpEngine() context=hlapi.ContextData() result = list() for (errorIndication, errorStatus, errorIndex, varBinds) in hlapi.nextCmd( engine, credentials, hlapi.UdpTransportTarget((target, port)), context, ObjectType(ObjectIdentity(oid)), lexicographicMode=not(table) ): if errorIndication: print('fail') time.sleep(1) elif errorStatus: print('fail') time.sleep(1) else: result.append(str(varBinds[0])) return result
def _walk(self): """SNMP Walk Returns: Dictionary with configurations fetched via SNMP. """ iterator = nextCmd( self.engine, CommunityData('public'), UdpTransportTarget((self.address, self.port)), ContextData(), ObjectType( ObjectIdentity(self.mib, '', 0).addMibSource(self.mib_dir))) res = {} for errorIndication, errorStatus, errorIndex, varBinds in iterator: if errorIndication: logger.error(errorIndication) elif errorStatus: logger.error( '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: logger.debug(varBind) varBindList = [x.prettyPrint() for x in varBind] key = varBindList[0].replace(self.mib + "::", "") if (len(varBindList) > 2): res[key] = tuple(varBindList[1:]) else: res[key] = varBindList[1] return res
def update(self): """Get the latest data from the remote SNMP capable host.""" from pysnmp.hlapi import (nextCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) for errindication, errstatus, errindex, restable in nextCmd( SnmpEngine(), CommunityData(self._community, mpModel=self._version), UdpTransportTarget((self._host, self._port)), ContextData(), ObjectType(ObjectIdentity(self._baseoid))): if errindication and not self._accept_errors: _LOGGER.error("SNMP error: %s", errindication) elif errstatus and not self._accept_errors: _LOGGER.error( "SNMP error: %s at %s", errstatus.prettyPrint(), errindex and restable[-1][int(errindex) - 1] or '?') elif (errindication or errstatus) and self._accept_errors: self.value = self._default_value else: for resrow in restable: self.attributes[str(resrow[0])] = resrow self.value = self._default_value errors = self.attributes.get('1.3.6.1.2.1.25.3.5.1.2.1') if errors: code = errors[1].asNumbers()[0] if code != 0: _LOGGER.info('Error code: %s', errors[1].asNumbers()) self.value = ERRORS.get(int(math.log(code, 2))) return status = self.attributes.get('1.3.6.1.2.1.25.3.5.1.1.1') if status: self.value = STATUS.get(status[-1])
def get_snmp_table_data(config, *args, snmp_engine=SnmpEngine(), snmpversion="2c"): """Retrieve necessary data via SNMP""" authdata = prepare_authdata(config, snmpversion) target = UdpTransportTarget((config["host"], config["port"])) snmp_data = [] for (error_indication, error_status, error_index, var_binds) in nextCmd( snmp_engine, authdata, target, ContextData(), *args, lexicographicMode=False, ): if error_indication: raise ValueError(error_indication) elif error_status: status = error_status.prettyPrint() index = error_index and var_binds[int(error_index) - 1][0] or "?" raise ValueError(f"{status} at {index}") else: snmp_data.append(var_binds) return snmp_data
def snmpWalk(snmpVersion, community, host, port, oid): generator = snmp.nextCmd(snmp.SnmpEngine(), snmp.CommunityData(community, mpModel=snmpVersion), snmp.UdpTransportTarget((host, port)), snmp.ContextData(), snmp.ObjectType(snmp.ObjectIdentity(oid)), lexicographicMode=False) results = dict() for errorIndication, errorStatus, errorIndex, varBinds in generator: if errorIndication: print(errorIndication) continue if errorStatus: print('%s at %s', errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?') continue for name, value in varBinds: results[str(name)] = str(value) return results
def table(self, objects: list) -> Dict[int, Dict[str, Any]]: res = {} for (error_indication, error_status, error_index, var_binds) in nextCmd(self.engine, self.cdata, self.target, ContextData(), *objects, lexicographicMode=False): if error_indication: logger.error('SNMP GET error_indication: %s', error_indication) raise RuntimeError( f'snmp table: error_indication: {error_indication}') elif error_status: logger.error( 'SNMP GET error_status: %s at %s', error_status, error_index and var_binds[int(error_index) - 1][0] or '?') loc = error_index and var_binds[int(error_index) - 1][0] or '?' raise RuntimeError( f'snmp table: error_status: {error_status} at ' f"{loc}") for varBind in var_binds: _, itemname, idx = self._decode_identity(varBind[0]) if idx not in res: res[idx] = {} res[idx][itemname] = varBind[1] return res
def _get_next(self, obj_identity): args = self.snmp_basic_info + (hlapi.ObjectType(obj_identity),) kwargs = {'lexicographicMode': False} result = {} for (errorIndication, errorStatus, errorIndex, varBinds) in hlapi.nextCmd(*args, **kwargs): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: res = self._parse_var_bind(varBind) value = varBind[1] if isinstance(value, rfc1902.Integer32): result[res[1]] = int(res[2]) else: result[res[1]] = varBind[1]._value.decode('utf-8') return result
def walk(self, oid): snmp_ret = nextCmd(SnmpEngine(), CommunityData(self.community), UdpTransportTarget((self.hostname, self.snmp_port)), ContextData(), ObjectType(ObjectIdentity(oid)), lexicographicMode=False) return self._to_list(snmp_ret=snmp_ret)
def get_next(target, oids, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): handler = hlapi.nextCmd( engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *construct_object_types_from_named_oid(oids) ) return fetch(handler)
def next_cmd(self, oid, max_rows=25, max_calls=0): ''' get next oid mib info ''' self.snmp_ret = nextCmd(SnmpEngine(), CommunityData(self.community), UdpTransportTarget( (self.router_ip, self.snmp_port)), ContextData(), ObjectType(ObjectIdentity(oid)), maxRows=max_rows, maxCalls=max_calls) return self._to_list()
def fetch_sysobject_oid(self, config): """Return the sysObjectID of the instance.""" # Reference sysObjectID directly, see http://oidref.com/1.3.6.1.2.1.1.2 oid = hlapi.ObjectType(hlapi.ObjectIdentity((1, 3, 6, 1, 2, 1, 1, 2))) self.log.debug('Running SNMP command on OID %s', oid) error_indication, error_status, error_index, var_binds = next( hlapi.nextCmd( config.snmp_engine, config.auth_data, config.transport, config.context_data, oid, lookupMib=False ) ) self.raise_on_error_indication(error_indication, config.ip_address) self.log.debug('Returned vars: %s', var_binds) return var_binds[0][1].prettyPrint()
def get_table(target, oids, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): handler = hlapi.nextCmd(engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *construct_object_types(oids), lexicographicMode=False) return fetch(handler, len(oids))
def get_ifs(conn): ifs = {} iftype = SnmpApi.ObjectType(SnmpApi.ObjectIdentity('IF-MIB', 'ifType')) ifname = SnmpApi.ObjectType(SnmpApi.ObjectIdentity('IF-MIB', 'ifName')) ifdescr = SnmpApi.ObjectType(SnmpApi.ObjectIdentity('IF-MIB', 'ifDescr')) ifalias = SnmpApi.ObjectType(SnmpApi.ObjectIdentity('IF-MIB', 'ifAlias')) for (errorIndication, errorStatus, errorIndex, varBinds) in SnmpApi.nextCmd(conn['snmpEng'], conn['community'], conn['target'], conn['context'], iftype, ifname, ifdescr, ifalias, lexicographicMode=False): if errorIndication: print(errorIndication) continue elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) continue for varBind in varBinds: (oid, value) = [x.prettyPrint() for x in varBind] if value is None: continue index = (oid.split('.'))[-1] if index not in ifs: ifs[index] = {} if re.search('ifType', oid): label = 'ifType' elif re.search('ifName', oid): label = 'ifName' elif re.search('ifDescr', oid): label = 'ifDescr' elif re.search('ifAlias', oid): label = 'ifAlias' else: continue ifs[index][label] = value return ifs
def snmp_walk(host, oid, format='str', strip_prefix=True, community='public'): res = [] for (errorIndication, errorStatus, errorIndex, varBinds) in hlapi.nextCmd( hlapi.SnmpEngine(), hlapi.CommunityData(community), hlapi.UdpTransportTarget((host, 161), timeout=4.0, retries=3), hlapi.ContextData(), hlapi.ObjectType(hlapi.ObjectIdentity(oid)), lookupMib=False, lexicographicMode=False): if errorIndication: raise ConnectionError( f'SNMP error: "{str(errorIndication)}". Status={str(errorStatus)}' ) elif errorStatus: raise ConnectionError( 'errorStatus: %s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for x in varBinds: k, v = x if strip_prefix: k = str(k)[len(str(oid)) + 1:] if isinstance(v, rfc1902.Integer): res.append((str(k), int(v))) else: if format == 'numbers': res.append((str(k), v.asNumbers())) elif format == 'hex': res.append((str(k), v.asOctets().hex())) elif format == 'raw': res.append((str(k), v)) elif format == 'bin': res.append((str(k), v.asOctets())) elif format == 'int': res.append((str(k), int(v))) elif format == 'preview': res.append((str(k), str(v))) elif format == 'any': try: res.append((str(k), v.asOctets().decode('utf-8'))) except UnicodeDecodeError: res.append((str(k), '0x' + v.asOctets().hex())) elif format == 'str': res.append((str(k), v.asOctets().decode(v.encoding))) else: assert False, "Unknown format for walk()." res = {a: b for a, b in res} return res
def get_table(target, oids, credentials, start_from=0, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): handler = hlapi.nextCmd(engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *construct_object_types_from_named_oid(oids), lexicographicMode=False) return cut_array_to_table(fetch(handler), len(oids))
def get_l2tp_session_stats(SNMP_target, auth_data, results, OID, data_as_index=False): # getting info about l2tp session # if data_as_index is True then SNMP data will be used is index and L2TPtunnel.LTPSession as value # if data_as_index is false then L2TPtunnel.LTPSession will be used is index and SNMP data as value thread_data = threading.local() print('Getting stats for OID: ', OID, flush=True) for (thread_data.errorIndication, thread_data.errorStatus, thread_data.errorIndex, thread_data.varBinds) in nextCmd(SnmpEngine(), auth_data, SNMP_target, ContextData(), ObjectType(ObjectIdentity(OID)), lexicographicMode=False): if thread_data.errorIndication: print(thread_data.errorIndication) break elif thread_data.errorStatus: print( '%s at %s' % (thread_data.errorStatus.prettyPrint(), thread_data.errorIndex and thread_data.varBinds[int(thread_data.errorIndex) - 1][0] or '?')) break else: for thread_data.varBind in thread_data.varBinds: thread_data.uid = str(thread_data.varBind[0]).split(".") if str(thread_data.varBind[1]) != "": if (data_as_index): results[str( thread_data.varBind[1] )] = thread_data.uid[-2] + '.' + thread_data.uid[-1] else: results[thread_data.uid[-2] + '.' + thread_data.uid[-1]] = str( thread_data.varBind[1]) print('Got ' + str(len(results)) + ' data entries for OID: ' + OID)
def get_next(self, oid): """Use PySNMP to perform an SNMP GET NEXT operation on a table object. :param oid: The OID of the object to get. :raises: SNMPFailure if an SNMP request fails. :returns: A list of values of the requested table object. """ try: snmp_gen = snmp.nextCmd(self.snmp_engine, self._get_auth(), self._get_transport(), self._get_context(), snmp.ObjectType(snmp.ObjectIdentity(oid)), lexicographicMode=False) except snmp_error.PySnmpError as e: raise exception.SNMPFailure(operation="GET_NEXT", error=e) vals = [] for (error_indication, error_status, error_index, var_binds) in snmp_gen: if error_indication: # SNMP engine-level error. raise exception.SNMPFailure(operation="GET_NEXT", error=error_indication) if error_status: # SNMP PDU error. raise exception.SNMPFailure(operation="GET_NEXT", error=error_status.prettyPrint()) # this is not a table, but a table row # e.g. 1-D array of tuples _name, value = var_binds[0] vals.append(value) return vals
def snmpwalk(ipaddress, community, oid): _results = [] for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData(community), UdpTransportTarget((ipaddress, 161)), ContextData(), ObjectType(oid), lexicographicMode=False, lookupMib=True): if errorIndication: raise Exception(f"Error performing snmpwalk: {errorIndication}") if errorStatus: _msg = '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?') raise Exception(f"Error performing snmpget: {_msg}") else: _results.append(varBinds) if len(_results) > 0: return _results return None
def get_int_stats(SNMP_target, auth_data, interface_data, OID): print('Getting stats for OID: ', OID, flush=True) thread_data = threading.local() for ( thread_data.errorIndication, thread_data.errorStatus, thread_data.errorIndex, thread_data.varBinds ) in nextCmd( SnmpEngine(), auth_data, SNMP_target, ContextData(), ObjectType(ObjectIdentity(OID)), # ObjectType(ObjectIdentity('1.3.6.1.2.1.31.1.1.1.6')), # (64 bit - but not supported by Cisco) lexicographicMode=False): if thread_data.errorIndication: print(thread_data.errorIndication) break elif thread_data.errorStatus: print( '%s at %s' % (thread_data.errorStatus.prettyPrint(), thread_data.errorIndex and thread_data.varBinds[int(thread_data.errorIndex) - 1][0] or '?')) break else: for thread_data.varBind in thread_data.varBinds: thread_data.uid = str(thread_data.varBind[0]).split(".") try: interface_data[str(thread_data.uid[-1])] = int( thread_data.varBind[1]) except KeyError: # print("Interface ID "+uid[-1]+" not found") pass print('Got ' + str(len(interface_data)) + ' data entries for OID: ' + OID)
def walk(host, oid, data, index): for i, (errorIndication, errorStatus, errorIndex, varBinds) in \ enumerate( nextCmd( SnmpEngine(), CommunityData(SNMP_COMMUNITY, mpModel=1), UdpTransportTarget((host, PORT)), ContextData(), ObjectType(ObjectIdentity(oid)), lexicographicMode=False ) ): if errorIndication: print(errorIndication, file=sys.stderr) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'), file=sys.stderr) break else: for varBind in varBinds: data[index].append(str(varBind).split("=")[1])
def storage_check(volumes_search): exit_code = exit_status_map["OK"] volume_errors = [] performance_data = [] cmd = nextCmd( engine, community, transport, context, ObjectType(ObjectIdentity('HOST-RESOURCES-MIB', 'hrStorageDescr')), ObjectType( ObjectIdentity('HOST-RESOURCES-MIB', 'hrStorageAllocationUnits').addMibSource('.')), ObjectType(ObjectIdentity('HOST-RESOURCES-MIB', 'hrStorageSize')), ObjectType(ObjectIdentity('HOST-RESOURCES-MIB', 'hrStorageUsed')), lexicographicMode=False) try: volumes_spec = get_volumes_spec_from_cmd(cmd, volumes_search) except ErrorIndication as e: exit_code = exit_status_map["UNKNOWN"] volume_errors.append(e) else: for volume_search in volumes_search: if volume_search in volumes_spec: volume_status = "OK" for volume_spec in volumes_spec[volume_search]: used_perc = volume_spec["used"] / volume_spec["size"] total_size = int(volume_spec["size"] / b_to_mb) # total size in MiB used_space = int(volume_spec["used"] / b_to_mb) # total size in MiB if used_perc > critical_threshold: volume_status = "CRITICAL" elif used_perc > warning_threshold: volume_status = "WARNING" if volume_status != "OK": volume_errors.append( volume_error_template.format( volume_status, volume_spec["name"], used_perc * 100)) performance_data.append( performance_template.format( volume_spec["name"], used_space, "MB", int(total_size * warning_threshold), int(total_size * critical_threshold), total_size)) if exit_code < exit_status_map[volume_status]: exit_code = exit_status_map[volume_status] else: volume_status = "CRITICAL" # performance_data.append(performance_template.format(volume_name, "-", "MB", "-", "-", "-")) volume_errors.append( not_found_message_template.format(volume_search)) exit_code = exit_status_map[volume_status] if len(volume_errors) > 0: print("Storage ERROR", *volume_errors, sep=" - ") else: print("All volumes OK") if len(performance_data) > 0: print("|" + " ".join(performance_data)) return exit_code
community = "community" #changeme #AnywhereUSB IP device_ip = sys.argv[1] #Server with key IP connected_ip = "hostip_with_key" #changeme #dictionary of all connections connections = {} #default result (no connections) result = 0 #snmp walk for take all connections to keys and add in dictionary for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData(community, mpModel=1), UdpTransportTarget((device_ip, 161)), ContextData(), ObjectType(ObjectIdentity("1.3.6.1.2.1.6.13.1.1")), lexicographicMode=False): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for oid, value in varBinds: connections[str(oid)] = str(value)
def if_check(interfaces_search): if_status = [] if_perf = [] if_error = [] exit_code = exit_status_map["OK"] cmd = nextCmd(engine, community, transport, context, ObjectType(ObjectIdentity('IF-MIB', 'ifIndex')), ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')), ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')), ObjectType(ObjectIdentity('IF-MIB', 'ifAdminStatus')), ObjectType(ObjectIdentity('IF-MIB', 'ifSpeed')), ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')), ObjectType(ObjectIdentity('IF-MIB', 'ifOutOctets')), lexicographicMode=False) timestamp = round(time.time()) try: ifs_spec = get_if_spec_from_cmd(cmd, interfaces_search) except ErrorIndication as e: exit_code = exit_status_map["UNKNOWN"] if_error.append(e) else: for if_search in interfaces_search: if if_search in ifs_spec: for if_spec in ifs_spec[if_search]: if_io_min = "-" if_io_max = "-" if_in_warning = "-" if_out_warning = "-" if_in_critical = "-" if_out_critical = "-" if_in_mbps = "-" if_out_mbps = "-" if_in_util = "-" if_out_util = "-" if_vlan = None if_name = if_spec["name"] if_oper_status = if_spec["status"] if_adm_status = if_spec["adm_status"] if_speed = if_spec["speed"] if_in_tot = if_spec["in"] if_out_tot = if_spec["out"] if get_vlan: err_ind, err_stat, err_idx, if_snmp = next( getCmd( engine, community, transport, context, ObjectType( ObjectIdentity('SNMPv2-SMI', 'enterprises', CISCO_VLAN_MEMBERSHIP, if_spec["index"])))) try: if_vlan = " - vLAN {}".format(int(if_snmp[0][1])) except ValueError: pass if_metrics = None if_file = "/tmp/_snmp-check_{}_{}".format( host, if_name.replace("/", "_")) try: with open(if_file, 'r') as data_file: if_metrics = json.load(data_file) except (OSError, ValueError): pass try: with open(if_file, 'w') as data_file: json.dump( { "timestamp": timestamp, "if_in_octets": if_in_tot, "if_out_octets": if_out_tot }, data_file) except OSError: pass if check_if_status: if if_oper_status != if_adm_status: exit_code = exit_status_map["WARNING"] if_error.append("{}: (is {} not {})".format( if_name, if_oper_status, if_adm_status)) if_oper_status = "({})".format(if_oper_status) if if_speed > 0: if_io_min = "0" if_io_max = "{:.2f}".format(if_speed / 1000000) if_in_warning = "{:.2f}".format( if_speed * warning_threshold[0] / 100000000) if_out_warning = "{:.2f}".format( if_speed * warning_threshold[1] / 100000000) if_in_critical = "{:.2f}".format( if_speed * critical_threshold[0] / 100000000) if_out_critical = "{:.2f}".format( if_speed * critical_threshold[1] / 100000000) if if_metrics is not None and if_spec["status"] == "UP": time_delta = timestamp - if_metrics['timestamp'] if not octects_only: if_in_mbps = "{:.2f}".format( (if_in_tot - if_metrics['if_in_octets']) * (8 / 1000000) / time_delta) if_out_mbps = "{:.2f}".format( (if_out_tot - if_metrics['if_out_octets']) * (8 / 1000000) / time_delta) if if_speed > 0: if_tot_band = time_delta * if_speed if_in_util = "{:.2f}".format( (if_in_tot - if_metrics['if_in_octets']) * 8 * 100 / if_tot_band) if_out_util = "{:.2f}".format( (if_out_tot - if_metrics['if_out_octets']) * 8 * 100 / if_tot_band) if_status.append("{}: ({}%,{}%) {}{}".format( if_name, if_in_util, if_out_util, if_oper_status, if_vlan if if_vlan is not None else "")) if octects_only: if_perf.append("'{} in'={}c".format( if_name, if_in_tot)) if_perf.append("'{} out'={}c".format( if_name, if_out_tot)) else: if_perf.append("'{} in'={}Mb;{};{};{};{}".format( if_name, if_in_mbps, if_in_warning, if_in_critical, if_io_min, if_io_max)) if_perf.append("'{} out'={}Mb;{};{};{};{}".format( if_name, if_out_mbps, if_out_warning, if_out_critical, if_io_min, if_io_max)) else: exit_code = exit_status_map["CRITICAL"] if_error.append("{}: {}".format(if_search, "interface not found")) if len(if_error) == 0: print("All interfaces OK") else: print("Interfaces ERROR", *if_error, sep=" - ") if len(if_status) > 0: print(*if_status, sep="\n") if len(if_perf) > 0: print("|" + " ".join(if_perf)) return exit_code
def _parse_mibs(iLOIP, snmp_credentials): """Parses the MIBs. :param iLOIP: IP address of the server on which SNMP discovery has to be executed. :param snmp_credentials: a Dictionary of SNMP credentials. auth_user: SNMP user auth_protocol: Auth Protocol auth_prot_pp: Pass phrase value for AuthProtocol. priv_protocol:Privacy Protocol. auth_priv_pp: Pass phrase value for Privacy Protocol. :returns the dictionary of parsed MIBs. :raises exception.InvalidInputError if pysnmp is unable to get SNMP data due to wrong inputs provided. :raises exception.IloError if pysnmp raises any exception. """ result = {} usm_user_obj = _create_usm_user_obj(snmp_credentials) try: for(errorIndication, errorStatus, errorIndex, varBinds) in hlapi.nextCmd( hlapi.SnmpEngine(), usm_user_obj, hlapi.UdpTransportTarget((iLOIP, 161), timeout=3, retries=3), hlapi.ContextData(), # cpqida cpqDaPhyDrvTable Drive Array Physical Drive Table hlapi.ObjectType( hlapi.ObjectIdentity('1.3.6.1.4.1.232.3.2.5.1')), # cpqscsi SCSI Physical Drive Table hlapi.ObjectType( hlapi.ObjectIdentity('1.3.6.1.4.1.232.5.2.4.1')), # cpqscsi SAS Physical Drive Table hlapi.ObjectType( hlapi.ObjectIdentity('1.3.6.1.4.1.232.5.5.2.1')), lexicographicMode=False, ignoreNonIncreasingOid=True): if errorIndication: LOG.error(errorIndication) msg = "SNMP failed to traverse MIBs %s", errorIndication raise exception.IloSNMPInvalidInputFailure(msg) else: if errorStatus: msg = ('Parsing MIBs failed. %s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[-1][int(errorIndex)-1] or '?' ) ) LOG.error(msg) raise exception.IloSNMPInvalidInputFailure(msg) else: for varBindTableRow in varBinds: name, val = tuple(varBindTableRow) oid, label, suffix = ( mibViewController.getNodeName(name)) key = name.prettyPrint() # Don't traverse outside the tables we requested if not (key.find("SNMPv2-SMI::enterprises.232.3") >= 0 or (key.find( "SNMPv2-SMI::enterprises.232.5") >= 0)): break if key not in result: result[key] = {} result[key][label[-1]] = {} result[key][label[-1]][suffix] = val except Exception as e: msg = "SNMP library failed with error %s", e LOG.error(msg) raise exception.IloSNMPExceptionFailure(msg) return result
def check_table( self, instance, snmp_engine, mib_view_controller, oids, lookup_names, timeout, retries, enforce_constraints=False, mibs_to_load=None, ): ''' Perform a snmpwalk on the domain specified by the oids, on the device configured in instance. lookup_names is a boolean to specify whether or not to use the mibs to resolve the name and values. Returns a dictionary: dict[oid/metric_name][row index] = value In case of scalar objects, the row index is just 0 ''' # UPDATE: We used to perform only a snmpgetnext command to fetch metric values. # It returns the wrong value when the OID passeed is referring to a specific leaf. # For example: # snmpgetnext -v2c -c public localhost:11111 1.3.6.1.2.1.25.4.2.1.7.222 # iso.3.6.1.2.1.25.4.2.1.7.224 = INTEGER: 2 # SOLUTION: perform a snmpget command and fallback with snmpgetnext if not found # Set aliases for snmpget and snmpgetnext with logging transport_target = self.get_transport_target(instance, timeout, retries) auth_data = self.get_auth_data(instance) context_engine_id, context_name = self.get_context_data(instance) first_oid = 0 all_binds = [] results = defaultdict(dict) while first_oid < len(oids): try: # Start with snmpget command oids_batch = oids[first_oid:first_oid + self.oid_batch_size] self.log.debug( "Running SNMP command get on OIDS {}".format(oids_batch)) error_indication, error_status, error_index, var_binds = next( hlapi.getCmd(snmp_engine, auth_data, transport_target, hlapi.ContextData(context_engine_id, context_name), *(oids_batch), lookupMib=enforce_constraints)) self.log.debug("Returned vars: {}".format(var_binds)) # Raise on error_indication self.raise_on_error_indication(error_indication, instance) missing_results = [] complete_results = [] for var in var_binds: result_oid, value = var if reply_invalid(value): oid_tuple = result_oid.asTuple() missing_results.append( hlapi.ObjectType(hlapi.ObjectIdentity(oid_tuple))) else: complete_results.append(var) if missing_results: # If we didn't catch the metric using snmpget, try snmpnext self.log.debug( "Running SNMP command getNext on OIDS {}".format( missing_results)) for error_indication, error_status, _, var_binds_table in hlapi.nextCmd( snmp_engine, auth_data, transport_target, hlapi.ContextData(context_engine_id, context_name), *missing_results, lookupMib=enforce_constraints, ignoreNonIncreasingOid=self. ignore_nonincreasing_oid, lexicographicMode= False # Don't walk through the entire MIB, stop at end of table ): self.log.debug( "Returned vars: {}".format(var_binds_table)) # Raise on error_indication self.raise_on_error_indication(error_indication, instance) if error_status: message = "{} for instance {}".format( error_status.prettyPrint(), instance["ip_address"]) instance["service_check_error"] = message # submit CRITICAL service check if we can't connect to device if 'unknownUserName' in message: instance[ "service_check_severity"] = Status.CRITICAL self.log.error(message) else: self.warning(message) for table_row in var_binds_table: complete_results.append(table_row) all_binds.extend(complete_results) except PySnmpError as e: if "service_check_error" not in instance: instance[ "service_check_error"] = "Fail to collect some metrics: {}".format( e) if "service_check_severity" not in instance: instance["service_check_severity"] = Status.CRITICAL self.warning("Fail to collect some metrics: {}".format(e)) # if we fail move onto next batch first_oid = first_oid + self.oid_batch_size # if we've collected some variables, it's not that bad. if "service_check_severity" in instance and len(all_binds): instance["service_check_severity"] = Status.WARNING for result_oid, value in all_binds: if lookup_names: if not enforce_constraints: # if enforce_constraints is false, then MIB resolution has not been done yet # so we need to do it manually. We have to specify the mibs that we will need # to resolve the name. oid_to_resolve = hlapi.ObjectIdentity( result_oid.asTuple()).loadMibs(*mibs_to_load) result_oid = oid_to_resolve.resolveWithMib( mib_view_controller) _, metric, indexes = result_oid.getMibSymbol() results[metric][indexes] = value else: oid = result_oid.asTuple() matching = ".".join([str(i) for i in oid]) results[matching] = value self.log.debug("Raw results: {}".format(results)) return results
def get_snmp_data(device): try: device_data = [] if(device["type"].upper() == 'DX-SNMP'): community = device["attributes"]["community"] host_name = device["attributes"]["host_name"] port = device["attributes"]["port"] oids = device["attributes"]["oid"] if (device["attributes"]["snmp_version"] == 1): snmp_version = 0 elif (device["attributes"]["snmp_version"] == 2): snmp_version = 1 if(host_name != ""): if(oids != ""): if(community != ""): if(snmp_version != ""): print("--- Reading SNMP Device Data ---") for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData( community, mpModel=snmp_version), UdpTransportTarget( (host_name, port)), ContextData(), ObjectType(ObjectIdentity(oids))): if errorIndication: print("--- Error: " + str(errorIndication)+" ---") return device_data, 1 elif errorStatus: print("--- Error ---") print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) print("--- Error End ---") return device_data, 1 else: for varBind in varBinds: data_point = [x.prettyPrint() for x in varBind] device_data.append( { data_point[0].split(":")[-1].replace(".", "_"): data_point[1] } ) print("--- Successfully Read SNMP Device Data ---") return device_data, 0 else: print( 'Device attribute missing or invalid: snmp_version') return [], 1 else: print('Device attribute missing or invalid: community') return [], 1 else: print('Device attribute missing or invalid: oid') return [], 1 else: print('Device attribute missing or invalid: host_name') return [], 1 else: print('Device not of type DX-SNMP') return [], 1 except Exception as e: # print(device) print('Error occured while reading snmp device: ', device['id'], e) # traceback.print_tb(e.__traceback__) return device_data, 1