def _get_context(self): """Return the SNMP context for an SNMP request. :returns: A :class: `pysnmp.hlapi.ContextData` object. :raises: :class:`pysnmp.error.PySnmpError` if SNMP context data is bad. """ return snmp.ContextData(contextEngineId=self.context_engine_id, contextName=self.context_name)
def set(target, value_pairs, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): handler = hlapi.setCmd(engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *construct_value_pairs(value_pairs)) return fetch(handler, 1)[0]
def get(target, oids, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): handler = hlapi.getCmd(engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *construct_object_types(oids)) return fetch(handler, 1)[0]
def get(self, oids): handler = hlapi.getCmd( hlapi.SnmpEngine(), hlapi.UsmUserData(userName=self.username, authKey=self.authKey, privKey=self.privKey, authProtocol=self.authProtocol, privProtocol=self.privProtocol), hlapi.UdpTransportTarget((self.host, 161)), hlapi.ContextData(), *self.__construct_object_types(oids)) return self.__fetch(handler, 1)[0]
def get_by_oid(self, oid): res = hlapi.getCmd( hlapi.SnmpEngine(), self.auth_data, hlapi.UdpTransportTarget(self.target), hlapi.ContextData(), hlapi.ObjectType(hlapi.ObjectIdentity(oid)), ) res = next(res) err_indication, err_status, err_index, var_binds = res return var_binds[0]
def _make_get(address, community, *objects, port=161, mp_model=1): """Construct a pySNMP get command. Defaults to SNMPv2c and port 161. """ engine = hlapi.SnmpEngine() community = hlapi.CommunityData(community, mpModel=mp_model) target = hlapi.UdpTransportTarget((address, port)) context = hlapi.ContextData() return hlapi.getCmd(engine, community, target, context, *objects)
def get_bulk(target, oids, credentials, count, start_from=0, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): handler = hlapi.bulkCmd( engine, credentials, hlapi.UdpTransportTarget((target, port)), context, start_from, count, *construct_object_types(oids) ) return fetch(handler, count)
def get_bulk2(self, oids, count, start_from=0): handler = hlapi.bulkCmd( hlapi.SnmpEngine(), hlapi.UsmUserData(userName=self.username, authKey=self.authKey, privKey=self.privKey, authProtocol=self.authProtocol, privProtocol=self.privProtocol), hlapi.UdpTransportTarget((self.host, 161)), hlapi.ContextData(), start_from, count, *self.__construct_object_types(oids)) return self.__fetchBulk(handler, count)
def set_one(target, oid, value, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): handler = hlapi.setCmd(engine, credentials, hlapi.UdpTransportTarget((target, port)), context, hlapi.ObjectType(hlapi.ObjectIdentity(oid), value)) return fetch(handler, 1)[0]
def get_bulk(target, oids, credentials, count, start_from=0, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): handler = hlapi.bulkCmd( engine, credentials, hlapi.UdpTransportTarget((target, port)), context, start_from, count, *construct_object_types_from_named_oid(oids), lexicographicMode=True ) return fetch(handler)
def get_bulk_auto(target, oids, credentials, count_oid, start_from=0, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): count = get(target, [count_oid], credentials, port, engine, context)[count_oid] return get_bulk(target, oids, credentials, count, start_from, port, engine, context)
def __init__(self, instance, warning, global_metrics, mibs_path, profiles, profiles_by_oid): self.instance = instance self.tags = instance.get('tags', []) self.metrics = instance.get('metrics', []) profile = instance.get('profile') if is_affirmative(instance.get('use_global_metrics', True)): self.metrics.extend(global_metrics) if profile: if profile not in profiles: raise ConfigurationError("Unknown profile '{}'".format(profile)) self.metrics.extend(profiles[profile]['definition']) self.enforce_constraints = is_affirmative(instance.get('enforce_mib_constraints', True)) self.snmp_engine, self.mib_view_controller = self.create_snmp_engine(mibs_path) self.ip_address = None self.ip_network = None self.discovered_instances = {} self.failing_instances = defaultdict(int) self.allowed_failures = int(instance.get('discovery_allowed_failures', self.DEFAULT_ALLOWED_FAILURES)) self.bulk_threshold = int(instance.get('bulk_threshold', self.DEFAULT_BULK_THRESHOLD)) timeout = int(instance.get('timeout', self.DEFAULT_TIMEOUT)) retries = int(instance.get('retries', self.DEFAULT_RETRIES)) ip_address = instance.get('ip_address') network_address = instance.get('network_address') if not ip_address and not network_address: raise ConfigurationError('An IP address or a network address needs to be specified') if ip_address and network_address: raise ConfigurationError('Only one of IP address and network address must be specified') if ip_address: self.transport = self.get_transport_target(instance, timeout, retries) self.ip_address = ip_address self.tags.append('snmp_device:{}'.format(self.ip_address)) if network_address: if isinstance(network_address, bytes): network_address = network_address.decode('utf-8') self.ip_network = ipaddress.ip_network(network_address) if not self.metrics and not profiles_by_oid: raise ConfigurationError('Instance should specify at least one metric or profiles should be defined') self.table_oids, self.raw_oids, self.mibs_to_load = self.parse_metrics( self.metrics, self.enforce_constraints, warning ) self.auth_data = self.get_auth_data(instance) self.context_data = hlapi.ContextData(*self.get_context_data(instance))
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_ports(self): """Fetch ports and their values via SNMP Returns: Dict[Dict[]]: ports and their values """ from pysnmp import hlapi vars = [ (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB', 'ifIndex')), 'index'), (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB', 'ifDescr')), 'descr'), (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB', 'ifSpeed')), 'speed'), (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB', 'ifOperStatus')), 'status'), (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB', 'ifInErrors')), 'inErrors'), (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB', 'ifHCInOctets')), 'inOctets'), (hlapi.ObjectType(hlapi.ObjectIdentity('IF-MIB', 'ifHCOutOctets')), 'outOctets'), ] ports = {} for (errorIndication, errorStatus, errorIndex, varBindTable) in hlapi.bulkCmd(hlapi.SnmpEngine(), hlapi.CommunityData('public'), hlapi.UdpTransportTarget( (self.hostname, 161)), hlapi.ContextData(), 0, 20, *[x[0] for x in vars], lexicographicMode=False): if errorIndication: Exception("snmp error {}".format(errorIndication)) elif errorStatus: Exception("snmp error {}".format(errorStatus)) else: port = {} for (key, val), (base, label) in zip(varBindTable, vars): index = key.getMibSymbol()[-1][0].prettyPrint() val = val.prettyPrint() if label == 'status': val = val.strip("'") port[label] = val ports[port.pop('index')] = port return ports
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_by_var(self, mib_name, var_name, position=None): oid = ((mib_name, var_name) if position is None else (mib_name, var_name, position)) res = hlapi.getCmd( hlapi.SnmpEngine(), self.auth_data, hlapi.UdpTransportTarget(self.target), hlapi.ContextData(), hlapi.ObjectType(hlapi.ObjectIdentity(*oid)), ) res = next(res) err_indication, err_status, err_index, var_binds = res return var_binds[0]
def get_bulk(self, oids, count, start_from=0, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): handler = hlapi.bulkCmd(engine, self.credentials, hlapi.UdpTransportTarget( (self.target, self.port)), context, start_from, count, *construct_object_types(oids), lexicographicMode=False) return self.fetch(handler, count)
def taskSnmp(oid, host, port, readcommunity): # sample oids of windows snmp service for debugging # NoSuchObject # oid=".0.0.0.0.0.0.0.0" # TimeTicks # oid=".1.3.6.1.2.1.1.3.0" # OID # oid=".1.3.6.1.2.1.1.2.0" # integer # oid=".1.3.6.1.2.1.1.7.0" # gauge # oid=".1.3.6.1.2.1.2.2.1.5.1" # Counter32 # oid=".1.3.6.1.2.1.2.2.1.10.1" # IpAddres # oid=".1.3.6.1.2.1.4.20.1.3.127.0.0.1" # OctetString # oid=".1.3.6.1.2.1.1.1.0" # OctetString with MAC addres # oid=".1.3.6.1.2.1.2.2.1.6.6" req = snmp.getCmd(snmp.SnmpEngine(), snmp.CommunityData(readcommunity), snmp.UdpTransportTarget((host, port)), snmp.ContextData(), snmp.ObjectType(snmp.ObjectIdentity(oid))) reply = next(req) if reply[0] is None: # ok result example(None, 0, 0, # [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.3.0')), # TimeTicks(1245987))]) varBind = reply[3][0] if oid[0] == ".": prefix = "." else: prefix = "" oidInResult = prefix + str(varBind[0]) if oidInResult != oid: return ("Указан неверный OID", str(oidInResult), oid) else: value = varBind[1] return _snmpFormatValue(value) else: # error example (RequestTimedOut('No SNMP response received before # timeout',), 0, 0, []) raise Exception(str(reply[0]))
def __init__(self, agent_ip, agent_port, community): self.agent_ip = agent_ip self.agent_port = agent_port # SNMPv2 community self.community = community self.engine = hlapi.SnmpEngine() self.community_data = hlapi.CommunityData(self.community) self.transport_target = hlapi.UdpTransportTarget( (self.agent_ip, self.agent_port)) self.context_data = hlapi.ContextData() self.snmp_basic_info = (self.engine, self.community_data, self.transport_target, self.context_data) super(SNMPv2Client, self).__init__()
def common(): """PySNMP Tutorial Common Operations Example""" engine = hlapi.SnmpEngine() community = hlapi.CommunityData("public", mpModel=1) # SNMPv2c target = hlapi.UdpTransportTarget(("192.168.0.59", 161)) context = hlapi.ContextData() # object_id = hlapi.ObjectIdentity( # "iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0" # ) sysDescr = hlapi.ObjectType( hlapi.ObjectIdentity("SNMPv2-MIB", "sysDescr", 0)) sysUpTime = hlapi.ObjectType( hlapi.ObjectIdentity("SNMPv2-MIB", "sysUpTime", 0)) ifInOctets = hlapi.ObjectType( hlapi.ObjectIdentity("IF-MIB", "ifInOctets", 1)) command = hlapi.getCmd(engine, community, target, context, sysDescr, sysUpTime, ifInOctets) _old_print_results(command)
def get(target, oids, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): """ Send a get SNMP request for a MIB list inputs: target (str) : Device IP address oids (str) : List or single MIB tuple (see pyconfig.py for examples) credentials (str) : SNMP Community data : Value to set. Must be casted according to rfc1902 OID type specification before calling outputs: SNMP response (dict) """ handler = hlapi.getCmd( engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *construct_object_types_from_named_oid(oids) ) return fetch(handler)
def get_bulk_auto(self, target, oids, community, count_oid, version=1, timeout=1, retries=3, start_from=0, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): count = self.get(target, [count_oid], community, port, version, timeout, retries, engine, context) if count == -1: return None else: return self.get_bulk(target, oids, community, count[count_oid], version, timeout, retries, start_from, port, engine, context)
def __init__(self, instance, warning, global_metrics, mibs_path): self.tags = instance.get('tags', []) self.metrics = instance.get('metrics', []) if is_affirmative(instance.get('use_global_metrics', True)): self.metrics.extend(global_metrics) self.enforce_constraints = is_affirmative( instance.get('enforce_mib_constraints', True)) self.snmp_engine, self.mib_view_controller = self.create_snmp_engine( mibs_path) timeout = int(instance.get('timeout', self.DEFAULT_TIMEOUT)) retries = int(instance.get('retries', self.DEFAULT_RETRIES)) self.transport = self.get_transport_target(instance, timeout, retries) self.ip_address = instance['ip_address'] self.table_oids, self.raw_oids, self.mibs_to_load = self.parse_metrics( self.metrics, self.enforce_constraints, warning) self.tags.append('snmp_device:{}'.format(self.ip_address)) self.auth_data = self.get_auth_data(instance) self.context_data = hlapi.ContextData(*self.get_context_data(instance))
def quickstart(): """PySNMP Quick Start Example""" iterator = hlapi.getCmd( hlapi.SnmpEngine(), hlapi.CommunityData("public", mpModel=0), hlapi.UdpTransportTarget(("192.168.0.59", 161)), hlapi.ContextData(), hlapi.ObjectType(hlapi.ObjectIdentity("SNMPv2-MIB", "sysDescr", 0)), ) errorIndication, errorStatus, errorIndex, varBinds = next(iterator) 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: print(" = ".join([x.prettyPrint() for x in varBind]))
def snmpGet(snmpVersion, community, host, port, oids): objectTypes = [snmp.ObjectType(snmp.ObjectIdentity(oid)) for oid in oids] errorIndication, errorStatus, errorIndex, varBinds = next( snmp.getCmd(snmp.SnmpEngine(), snmp.CommunityData(community, mpModel=snmpVersion), snmp.UdpTransportTarget((host, port)), snmp.ContextData(), *objectTypes)) if errorIndication: print(errorIndication) return None if errorStatus: print('%s at %s', errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?') return None results = [(str(name), str(value)) for name, value in varBinds] return dict(results)
def get_oid(target, oid, credentials): """ Send a set SNMP request for a single OID inputs: target (str) : Device IP address oid (str) : Single OID to get credentials (str) : SNMP Community outputs: SNMP response (dict) """ port=161 engine=hlapi.SnmpEngine() context=hlapi.ContextData() handler = hlapi.getCmd( engine, credentials, hlapi.UdpTransportTarget((target, port)), context, ObjectType(ObjectIdentity(oid)) ) return fetch(handler)
def snmp_get(target, communityname, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): """ Constuctor function for fetching OID data from device. @params: target - Required : IP address of the device (Str) communityname - Required : SNMP community name (Str) port - Optional : UDP port for SNMP request (Int) engine - Optional : SNMP engine for request, from pysnmp hlapi (Obj) context - Optional : SNMP context data for request, from pysnmp hlapi (Obj) @return: fetch() : Dictionary of OID values from fetch function. """ model = '.1.3.6.1.2.1.1.1.0' serial = '.1.3.6.1.2.1.43.5.1.1.17.1' location = '.1.3.6.1.2.1.1.6.0' firmware = '.1.3.6.1.4.1.18334.1.1.1.5.5.1.1.3.1' hostname = '.1.3.6.1.4.1.18334.1.1.2.1.5.7.1.1.1.12.1' domain = '.1.3.6.1.4.1.18334.1.1.2.1.5.7.1.1.1.13.1' ip_address = '.1.3.6.1.4.1.18334.1.1.2.1.5.7.1.1.1.3.1' subnet = '.1.3.6.1.4.1.18334.1.1.2.1.5.7.1.1.1.4.1' gateway = '.1.3.6.1.4.1.18334.1.1.2.1.5.7.1.1.1.5.1' primary_dns = '.1.3.6.1.4.1.18334.1.1.2.1.5.7.1.2.1.3.1.1' secondary_dns = '.1.3.6.1.4.1.18334.1.1.2.1.5.7.1.2.1.3.1.2' oids = [ model, serial, location, firmware, hostname, domain, ip_address, subnet, gateway, primary_dns, secondary_dns ] handler = hlapi.getCmd(engine, communityname, hlapi.UdpTransportTarget((target, port)), context, *construct_object_types(oids)) return fetch(handler, 1)
def set_oid(target, oids, credentials,data): """ Send a set SNMP request for a single OID inputs: target (str) : Device IP address oids (str) : Single OID to set credentials (str) : SNMP Community data : Value to set. Must be casted according to rfc1902 OID type specification before calling outputs: SNMP response (dict) """ port=161 engine=hlapi.SnmpEngine() context=hlapi.ContextData() handler = hlapi.setCmd( engine, credentials, hlapi.UdpTransportTarget((target, port)), context, ObjectType(ObjectIdentity(oids),data) ) return fetch(handler)
def set(oid, value, host, port=161, community='private', timeout=0, retries=0, snmp_ver=2): """ Args: oid: SNMP OID or MIB name value: value to set host: target host port: target port (default: 161) community: SNMP community (default: public) timeout: max SNMP timeout retries: max retry count (default: 0) snmp_ver: SNMP version (default: 2) Returns: True if value is set, False if not """ try: for (err_i, err_st, err_idx, vals) in snmp_engine.setCmd( snmp_engine.SnmpEngine(), snmp_engine.CommunityData(community, mpModel=snmp_ver - 1), snmp_engine.UdpTransportTarget( (host, port), timeout=timeout, retries=retries), snmp_engine.ContextData(), snmp_engine.ObjectType(snmp_engine.ObjectIdentity(oid), value)): if err_i or err_st: logging.debug('snmp error: %s' % err_i) return None else: return True except: log_traceback() return False