def test_snmp(target, port=161, community='public'): try: errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), # mpModel -> 0:v1,1:v2c CommunityData(community, mpModel=1), UdpTransportTarget( (target, int(port)), timeout=1, retries=1), ContextData(), ObjectType(ObjectIdentity( 'SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', 0))) ) if errorIndication: return (False, errorIndication) elif errorStatus: msg = '%s at %s' % (errorStatus.prettyPrint( ), errorIndex and varBinds[int(errorIndex) - 1][0] or '?') return (False, msg) else: result = [] for varBind in varBinds: result.append(' = '.join( [x.prettyPrint() for x in varBind])) return (True, result) except Exception as e: # raise return (False, str(e))
def probe_oper_status(player): switch = current_app.config['SWITCHES'][player] address = switch['address'] port = switch['port'] logger.info("Probing status for player %d on switch %s:%d", player, address) engine = SnmpEngine() auth_data = CommunityData(switch['community'], mpModel=1) transport = UdpTransportTarget((address, port)) interfaces = switch['interfaces'] oper_states = [] for chunk in chunked( (ObjectType(ObjectIdentity(ifOperStatus.oid + (index, )), Null()) for index in interfaces), 24): cmd = getCmd(engine, auth_data, transport, ContextData(), *chunk) errorIndication, errorStatus, errorIndex, varBinds = next(cmd) if errorIndication is not None: raise Exception("SNMP error returned") oper_states.extend( ifOperStatus(int(value)) for identity, value in varBinds) with StateLock: for cell_state, (index, oper_state) in zip(current_app.cell_state[player], enumerate(oper_states)): if oper_state == ifOperStatus.down and cell_state != CellState.EMPTY: current_app.cell_state[player][index] = CellState.PRESENT if oper_state == ifOperStatus.up and cell_state != CellState.EMPTY: current_app.cell_state[player][index] = CellState.HIT if not any(cell_state == CellState.PRESENT for cell_state in current_app.cell_state[player]): current_app.game_state = GameState.OVER return True return False
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the SNMP sensor.""" from pysnmp.hlapi import ( getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) community = config.get(CONF_COMMUNITY) baseoid = config.get(CONF_BASEOID) unit = config.get(CONF_UNIT_OF_MEASUREMENT) version = config.get(CONF_VERSION) errindication, _, _, _ = next( getCmd(SnmpEngine(), CommunityData(community, mpModel=SNMP_VERSIONS[version]), UdpTransportTarget((host, port)), ContextData(), ObjectType(ObjectIdentity(baseoid)))) if errindication: _LOGGER.error("Please check the details in the configuration file") return False else: data = SnmpData(host, port, community, baseoid, version) add_devices([SnmpSensor(data, name, unit)])
def _oid_get(self, oid): """ Performs SNMP get command and returns OID value by sending a SNMP Get message. Args: oid (str): Full OID identifying the object to be read. Return: OID value (int) """ errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(self._snmp_engine, self._community_data, self._udp_transport_target, self._context, ObjectType(ObjectIdentity(oid)))) if errorIndication: msg = 'Found PDU errorIndication: {}'.format(errorIndication) logger.exception(msg) raise RuntimeError(msg) elif errorStatus: msg = 'Found PDU errorStatus: {}'.format(errorStatus) logger.exception(msg) raise RuntimeError(msg) return int(str(varBinds[-1]).partition('= ')[-1])
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the SNMP sensor.""" from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) host = config.get(CONF_HOST) port = config.get(CONF_PORT, DEFAULT_PORT) community = config.get(CONF_COMMUNITY, DEFAULT_COMMUNITY) baseoid = config.get(CONF_BASEOID) errindication, _, _, _ = next( getCmd(SnmpEngine(), CommunityData(community, mpModel=0), UdpTransportTarget((host, port)), ContextData(), ObjectType(ObjectIdentity(baseoid)))) if errindication: _LOGGER.error('Please check the details in the configuration file') return False else: data = SnmpData(host, port, community, baseoid) add_devices([ SnmpSensor(data, config.get('name', DEFAULT_NAME), config.get('unit_of_measurement')) ])
def snmp_connect(self): error_indication, error_status, error_index, var_binds = next( getCmd( SnmpEngine(), CommunityData('public'), UdpTransportTarget((self.entry.get_ip(), 161), timeout=self.entry.get_timeout(161), retries=1), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0')))) if error_indication: result = -1 elif error_status: result = -1 else: result = "OK" return result
def update(self): """Get the latest data from the remote SNMP capable host.""" from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) from brother_ql.reader import interpret_response errindication, errstatus, errindex, restable = next( getCmd(SnmpEngine(), CommunityData(self._community, mpModel=0), UdpTransportTarget((self._host, self._port)), ContextData(), ObjectType(ObjectIdentity(self._baseoid)))) if errindication: _LOGGER.error("SNMP error: %s", errindication) elif errstatus: _LOGGER.error("SNMP error: %s at %s", errstatus.prettyPrint(), errindex and restable[-1][int(errindex) - 1] or '?') else: assert len(restable) == 1 status = interpret_response(bytes(restable[0][1])) self.media_type = status['media_type'] self.media_width = '{} mm'.format(status['media_width']) self.media_length = status['media_length'] or 'endless' self.phase = status['phase_type'] self.errors = ', '.join(status['errors']) or '-none-' if status['errors']: self.state = 'error' elif 'waiting' in status['phase_type'].lower(): self.state = 'idle' elif 'printing' in status['phase_type'].lower(): self.state = 'printing' else: self.state = STATE_UNKNOWN
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the SNMP sensor.""" from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) community = config.get(CONF_COMMUNITY) baseoid = config.get(CONF_BASEOID) unit = config.get(CONF_UNIT_OF_MEASUREMENT) version = config.get(CONF_VERSION) accept_errors = config.get(CONF_ACCEPT_ERRORS) default_value = config.get(CONF_DEFAULT_VALUE) value_template = config.get(CONF_VALUE_TEMPLATE) if value_template is not None: value_template.hass = hass errindication, _, _, _ = next( getCmd(SnmpEngine(), CommunityData(community, mpModel=SNMP_VERSIONS[version]), UdpTransportTarget((host, port)), ContextData(), ObjectType(ObjectIdentity(baseoid)))) if errindication and not accept_errors: _LOGGER.error("Please check the details in the configuration file") return False else: data = SnmpData(host, port, community, baseoid, version, accept_errors, default_value) add_devices([SnmpSensor(data, name, unit, value_template)], True)
def set_outlet_on(self, outlet, on): """ Set an outlet on or off :param outlet: Which outlet to set the power for (for my model this is in the range 1 through 8) :param on: INVALID ATM True means turn it on, False means turn it off """ oid = ObjectIdentity( "1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.{}".format(outlet)) if isinstance(on, bool): target_state = "immediateOn" if on else "immediateOff" else: target_state = on errorIndication, errorStatus, errorIndex, varBinds = next( setCmd( SnmpEngine(), CommunityData("private"), UdpTransportTarget((self.host, 161)), ContextData(), ObjectType(oid, Integer32(self.outlet_state_oids[target_state])), )) if errorIndication: raise CyberPowerPduException(errorIndication) elif errorStatus: raise CyberPowerPduException("%s at %s" % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or "?", ))
def update(self): """Update the state.""" from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) from pyasn1.type.univ import (Integer) request = getCmd(SnmpEngine(), CommunityData(self._community, mpModel=self._version), UdpTransportTarget((self._host, self._port)), ContextData(), ObjectType(ObjectIdentity(self._baseoid))) errindication, errstatus, errindex, restable = next(request) if errindication: _LOGGER.error("SNMP error: %s", errindication) elif errstatus: _LOGGER.error("SNMP error: %s at %s", errstatus.prettyPrint(), errindex and restable[-1][int(errindex) - 1] or '?') else: for resrow in restable: if resrow[-1] == Integer(self._payload_on): self._state = True elif resrow[-1] == Integer(self._payload_off): self._state = False else: self._state = None
def snmp_harvester(ip: str, port: int, community: str, parameters: typing.Iterable[str]) -> t_snmp_samples_chunk: """ Fires SNMP GET query at endpoint defined by ip and port. The query consists all of OIDs defined in parameters argument. :param ip: host IP address :param port: SNMP port number :param community: community name :param parameters: list of OIDs :returns: samples as list of pairs: OID and its collected value """ if ipaddress.ip_address(ip).version == 4: transport = UdpTransportTarget else: transport = Udp6TransportTarget result = getCmd(SnmpEngine(), CommunityData(community, mpModel=1), transport((ip, port)), ContextData(), *[ObjectType(ObjectIdentity(oid)) for oid in parameters]) _error_indication, _error_status, _error_index, var_binds = next(result) return [(str(name), value._value) for name, value in var_binds if not isinstance(value, Null)]
def test_snmp_works(self): for series in ['xenial', 'bionic', 'cosmic', 'disco']: status = zaza.model.get_status() \ .applications['ubuntu-{}'.format(series)] for unit in status["units"]: details = status['units'][unit] address = details['public-address'] errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget((address, 161)), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0'))) ) self.assertIsNone(errorIndication)
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 _create_cmd_generator(self, object_identity, cmd_command): """ Generates the getCmd (see pySNMP doc) required to retrieve information from the agent. :raises: SnmpVersionException: if the SNMP version specified is not valid. :param object_identity: pySNMP object identity corresponding to the information we are looking for :return: cmd_command result """ if self.snmp_version == 1 or self.snmp_version == 2: data = CommunityData(self.community_index, mpModel=self.snmp_version - 1) return cmd_command( SnmpEngine(), data, UdpTransportTarget((self.server_address, self.snmp_port)), ContextData(), ObjectType(object_identity), lexicographicMode=False ) # STOPS WALKS WITHOUT CROSSING BOUNDARIES # EXAMPLE: IF WE GIVE OID 1.3.6.1.2.1.25.4.2.1.2, WE WILL ONLY WALK 1.3.6.1.2.1.25.4.2.1.2.X VALUES. IF THIS IS TRUE, WE WALK THE WHOLE TREE AFTER 1.3.6.1.2.1.25.4.2.1.2 SNMP_LOGGER.error( "SNMPv%d does not currently exist or isn't supported by this query", self.snmp_version) raise SnmpVersionException( "SNMPv%d does not currently exist or isn't supported by this query" % self.snmp_version)
def create_object_identity(self, **kwargs): """ :param oid: **REQUIRED** OID or MibSymbol value: **OPTION** value for snmp set :return: ObjectIdentity """ t.log("DEBUG", "Entering 'create_object_identity'\n"+__file__) oid = kwargs.get('oid') value = kwargs.get('value') oidre = re.match(r'(.*)::(.*)\.(.*)', oid) mib_name = '' oid_name = '' if oidre: mib_name = oidre.group(1) oid_name = oidre.group(2) oid_index = oidre.group(3) object_identity = ObjectIdentity( mib_name, oid_name, oid_index).addAsn1MibSource(self.mibs_dir) else: oidre = re.match('(.*)::(.*)', oid) if oidre: mib_name = oidre.group(1) oid_name = oidre.group(2) object_identity = ObjectIdentity(mib_name, oid_name).addAsn1MibSource(self.mibs_dir) if re.match(r'^([0-9]*\.)*[0-9]*$', oid): object_identity = ObjectIdentity(oid).addAsn1MibSource( self.mibs_dir) elif re.match(r'^([a-z A-Z 0-9 \-]*\.)*[a-z A-Z 0-9 \-]*$', oid): from pysnmp.smi import builder, view mibbuilder = builder.MibBuilder() mibviewcontroller = view.MibViewController(mibbuilder) objectidentity1 = ObjectIdentity(oid) objectidentity1.resolveWithMib(mibviewcontroller) oid = '.'.join(map(str, objectidentity1.getOid().asTuple())) object_identity = ObjectIdentity(oid).addAsn1MibSource( self.mibs_dir) if self.mibs_custom_dir: t.log('DEBUG', "Created Object Identity with custom mib directory: "+self.mibs_custom_dir) object_identity = object_identity.addMibSource(self.mibs_custom_dir) if value: object_type = ObjectType(object_identity, value) else: object_type = ObjectType(object_identity) return object_type
def get_cmd(self, oid): """ SNMP get """ snmp_ret = getCmd(SnmpEngine(), self.get_auth(), UdpTransportTarget((self.hostname, self.snmp_port)), ContextData(), ObjectType(ObjectIdentity(oid))) return self._to_list(snmp_ret=snmp_ret)
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 define_request(source, ip, community, snmp_version, fileconfname, pathfile, protocol, srvprovision, enableconfstart, urlfirmware, enablereboot): if snmp_version == '2c': communityData = CommunityData(community, mpModel=1) if snmp_version == '1': communityData = CommunityData(community, mpModel=0) if source: assd = AsynsockDispatcher() sock_transport = udp.UdpSocketTransport() sock_transport.socket.setsockopt(socket.SOL_SOCKET, 25, source + '\0') snmp_engine = engine.SnmpEngine() assd.registerTransport(udp.domainName, sock_transport) snmp_engine.registerTransportDispatcher(assd) else: snmp_engine = engine.SnmpEngine() varBind = [] result = [] for errorIndication, errorStatus, errorIndex, varBinds in setCmd( snmp_engine, communityData, UdpTransportTarget((ip, 161)), ContextData(), ObjectType( ObjectIdentity( '1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.100.0'), OctetString(fileconfname)), ObjectType( ObjectIdentity( '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.300.0'), OctetString(pathfile)), ObjectType( ObjectIdentity( '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.400.100.0'), Integer32(protocol)), ObjectType( ObjectIdentity( '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.400.400.0'), OctetString(srvprovision)), ObjectType( ObjectIdentity( '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.500.100.0'), Integer32(enableconfstart)), ObjectType( ObjectIdentity( '.1.3.6.1.4.1.4935.1000.100.200.100.1300.1.450.0'), OctetString(urlfirmware)), ObjectType( ObjectIdentity( '.1.3.6.1.4.1.4935.1000.100.200.100.1300.1.500.0'), Integer32(enablereboot))): varBind.append(varBinds) for i in varBinds: i = str(i) i = i.split('=')[1] result.append(i) # result.append(str(i)) # varBind = varBind.split('=')[1] # result.append(varBind) return result
def _create_notification_type(event_context): event_type = event_context['event_type'] workflow_id = event_context['workflow_id'] execution_id = event_context['execution_id'] tenant_name = event_context['tenant_name'] deployment_id = event_context['deployment_id'] or '' timestamp = _get_epoch_time(event_context) execution_parameters = _get_execution_parameters(event_context) notification_type = NotificationType( ObjectIdentity(CLOUDIFY_MIB, notification_types[event_type])) notification_type.addVarBinds( ObjectType(ObjectIdentity(CLOUDIFY_MIB, EXECUTION_ID), execution_id), ObjectType(ObjectIdentity(CLOUDIFY_MIB, WORKFLOW_NAME), workflow_id), ObjectType(ObjectIdentity(CLOUDIFY_MIB, TENANT_NAME), tenant_name), ObjectType(ObjectIdentity(CLOUDIFY_MIB, DEPLOYMENT_ID), deployment_id), ObjectType(ObjectIdentity(CLOUDIFY_MIB, TIMESTAMP), timestamp), ObjectType(ObjectIdentity(CLOUDIFY_MIB, WORKFLOW_PARAMETERS), execution_parameters)) if event_type == 'workflow_failed': error = _get_error(event_context) notification_type.addVarBinds( ObjectType(ObjectIdentity(CLOUDIFY_MIB, ERROR), error)) return notification_type
def get_pdu(self, message): # Properties of the managed object within the device are # arranged in this MIB tree structure. the complete path from the # top of the tree is ODI # Iso(1).org(3).dod(6).internet(1).private(4).2312.19.1.0 pdu = [ ObjectType(ObjectIdentity('1.3.6.1.4.2312.19.1.0'), OctetString(message))] return pdu
def make_value(parameter): """ Takes given parameter and returns it recreated and filled in with value. :param parameter: SNMP parameter :return: SNMP parameter with value """ parameter._ObjectType__state = ObjectType.stClean parameter._ObjectType__args[0].__stage = ObjectIdentity.stClean identity, _value = parameter oid = str(identity._ObjectIdentity__args[0]) identity = ObjectIdentity(oid) identity._ObjectIdentity__oid = oid identity._ObjectIdentity__state = ObjectIdentity.stClean val = ObjectType(identity, cls(value)) val._ObjectType__state = ObjectType.stClean return val
def set_outlet_on(self, outlet, on): """ Set an outlet on or off :param outlet: Which outlet to set the power for (for my model this is in the range 1 through 8) :param on: True means turn it on, False means turn it off """ # OK, sorry for this insane code - the pysnmp docs explicitly say you # should just copy paste their examples. # This is based on the code from here: # http://snmplabs.com/pysnmp/examples/hlapi/asyncore/sync/manager/cmdgen/modifying-variables.html # The command we would run to power on outlet 1 on the PDU, if we were # not masochists is this: # # snmpset -v 1 -c private $IPADDR CPS-MIB::ePDUOutletControlOutletCommand.1 i immediateOn # # However to get those human-readable names to work we'd need to # download MIBs and tell pysnmp about them. pysnmp + pysmi apparently # know how to do this but I tried to point it at the CyberPower MIB file # and it failed silently so huffed and gave up. # # So instead, we're going to do something more akin to this command, # which is exactly the same thing but without the human-readable names: # # snmpset -v 1 -c private $IPADDR .1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.2 i 1 # # In that command ".1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.2" is the # masochistic name for "CPS-MIB::ePDUOutletControlOutletCommand.2" and # "1" is the masochistic name for "immediateOn" # # I figured out what that command would be by running this: # snmptranslate -On CPS-MIB::ePDUOutletControlOutletCommand # # SnmpEngine and ContextData are just pointless boilerplate required by # pysnmp. Hopefully you can sort of see how the other bits map to the # code below (the "i" becaomse "Integer32"). oid = ObjectIdentity( '1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.{}'.format(outlet)) target_state = 'immediateOn' if on else 'immediateOff' errorIndication, errorStatus, errorIndex, varBinds = next( setCmd( SnmpEngine(), CommunityData('private'), UdpTransportTarget((self.host, 161)), ContextData(), ObjectType(oid, Integer32(self.outlet_state_oids[target_state])))) if errorIndication: raise CyberPowerPduException(errorIndication) elif errorStatus: raise CyberPowerPduException( '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
def get_cmd(self, oid): ''' get oid mib info ''' self.snmp_ret = getCmd(SnmpEngine(), self.get_auth(), UdpTransportTarget( (self.router_ip, self.snmp_port)), ContextData(), ObjectType(ObjectIdentity(oid))) return self._to_list()
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 _set(self, value): from pysnmp.hlapi import (setCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity) request = setCmd(SnmpEngine(), CommunityData(self._community, mpModel=self._version), UdpTransportTarget((self._host, self._port)), ContextData(), ObjectType(ObjectIdentity(self._baseoid), value)) next(request)
def _get(self, *variables): """Get one or more variables via SNMP Args: Tuple with the variables to fetch via SNMP. Returns: List of tuples with the fetched keys and values. """ obj_types = [] for var in variables: if isinstance(var, tuple): obj = ObjectType( ObjectIdentity(self.mib, var[0], var[1]).addMibSource(self.mib_dir)) else: obj = ObjectType( ObjectIdentity(self.mib, var, 0).addMibSource(self.mib_dir)) obj_types.append(obj) errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(self.engine, CommunityData('public'), UdpTransportTarget((self.address, self.port)), ContextData(), *obj_types)) if errorIndication: logger.error(errorIndication) elif errorStatus: logger.error( '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: res = list() for varBind in varBinds: logger.debug(' = '.join([x.prettyPrint() for x in varBind])) res.append(tuple([x.prettyPrint() for x in varBind])) return res
def __build_oid_groups(self, oid_groups, path): """ Build a list of ObjectType( ObjectIdentifier() ) for all the oids specified in 'oid_groups'. 'oid_groups' is a dict of key -> lists, and each element of the list is a string with an OID/variable name 'path' is a path on the filesystem that contains MIB definitions. """ groups = {} if not oid_groups: return groups # regex to match MIB::variable mib_re = re.compile("^([^:]+)::(.+)$") # for each item in oid_groups for group, oids in six.iteritems(oid_groups): objects = [] # get the list of oids for oid in oids: # check to see if it's an oid or a variable name match = mib_re.match(oid) if match: # it's a variable name, so make sure to add the MIB path to the # ObjectIdentity identity = ObjectIdentity(match.group(1), match.group(2), 1) if path: identity = identity.addAsn1MibSource(path) objects.append(ObjectType(identity)) else: # just a regular oid objects.append(ObjectType(ObjectIdentity(oid))) # if we have values, add to the result if objects: groups[group] = objects return groups
def bulk_cmd(self, oid, non_repeaters=0, max_repeaters=1): ''' bulk get router info by oid ''' self.snmp_ret = bulkCmd(SnmpEngine(), CommunityData(self.community), UdpTransportTarget( (self.router_ip, self.snmp_port)), ContextData(), non_repeaters, max_repeaters, ObjectType(ObjectIdentity(oid)), maxCalls=10) return self._to_list(oid)
def run(self, onetime: bool = False, interval: int = 10): logger.debug('Getting iterface names and aliases') for idx, vals in self.table([ ObjectType(ObjectIdentity('IF-MIB', 'ifName')), ObjectType(ObjectIdentity('IF-MIB', 'ifAlias')), ]).items(): self.if_names[idx] = self._decode_value(vals['ifName']) self.if_aliases[idx] = self._decode_value(vals['ifAlias']) self.if_metric_names[idx] = self._metric_for_if( self.if_names[idx], self.if_aliases[idx], idx) logger.debug('Set ifNames: %s', self.if_names) logger.debug('Set ifAliases: %s', self.if_aliases) logger.info('Set if_metric_names: %s', self.if_metric_names) while True: start = time.time() self.do_iteration(interval=interval) if onetime: break duration = time.time() - start if duration < interval: logger.debug('Sleep %s seconds', interval - duration) time.sleep(interval - duration)