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_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(target, oids, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): print(get) handler = hlapi.getCmd(engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *construct_object_types(oids)) print(handler) return fetch(handler, 1)[0]
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 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 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 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 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 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_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 get( target, oids, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData(), ): handler = hlapi.getCmd( engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *PullerSnmpThread.construct_object_types(oids) ) return PullerSnmpThread.fetch(handler, 1)[0]
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 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 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 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
def add_row(target, oids_and_values,credentials): """ Send a set SNMP request for row creation (=list) using MIB inputs: target (str) : Device IP address oids_and_values list(MIB entry) : List of MIB entries (as tuples, see pyconfig.py for examples) credentials (str) : SNMP Community outputs: SNMP response (dict) """ port=161 engine=hlapi.SnmpEngine() context=hlapi.ContextData() ObjectList=list() handler = hlapi.setCmd( engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *construct_object_types_from_name_set(oids_and_values) ) print(handler) return fetch(handler)
def get_value(self, oid): errorIndication, errorStatus, errorIndex, varBinds = next( 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(), hlapi.ObjectType(hlapi.ObjectIdentity(oid)))) 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(varBind) print(' = '.join([x.prettyPrint() for x in varBind]))
def snmp_set(target, value_pairs, communityname, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): """ Constuctor function for setting OID data to device. Values set are returned back. @params: target - Required : IP address of the device (Str) value_pairs - Required : Dictionary of OIDs and values, where OID is the key. (Dict) 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. """ handler = hlapi.setCmd(engine, communityname, hlapi.UdpTransportTarget((target, port)), context, *construct_value_pairs(value_pairs)) return fetch(handler, 1)
def get_oids(target, oids, credentials): """ Send a get SNMP request for an OID list inputs: target (str) : Device IP address oids (str) : List of OIDs credentials (str) : SNMP Community outputs: SNMP response (dict) """ port=161 engine=hlapi.SnmpEngine() context=hlapi.ContextData() ObjectList=list() for oid in oids: ObjectList.append(ObjectType(ObjectIdentity(oid))) handler = hlapi.getCmd( engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *ObjectList ) return fetch(handler)
def snmpSet(self, value_pairs, credentials='', port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()): target = self.__dut_ip if self.__snmp_ver.lower() == '2c': credentials = hlapi.CommunityData('private') handler = hlapi.setCmd(engine, credentials, hlapi.UdpTransportTarget((target, port)), context, *construct_value_pairs(value_pairs)) ret = fetch(handler, 1)[0] ret_list = [] for key, value in ret.items(): temp = key + ': ' + value ret_list.append(temp) UI.log('SNMP-SET', 'Remote IP: ' + self.__dut_ip, *ret_list) return ret
def send_snmp_trap(config, trap_data): """ Send a SNMP v2c trap. :param config: The configuration data. :type config: dict :param trap_data: """ oids = { 'alertname': '{}.1.1.1'.format(config['trap_oid_prefix']), 'status': '{}.1.1.2'.format(config['trap_oid_prefix']), 'severity': '{}.1.1.3'.format(config['trap_oid_prefix']), 'instance': '{}.1.1.4'.format(config['trap_oid_prefix']), 'job': '{}.1.1.5'.format(config['trap_oid_prefix']), 'description': '{}.1.1.6'.format(config['trap_oid_prefix']), 'labels': '{}.1.1.7'.format(config['trap_oid_prefix']), 'timestamp': '{}.1.1.8'.format(config['trap_oid_prefix']), 'rawdata': '{}.1.1.9'.format(config['trap_oid_prefix']) } transport_addr = (config['snmp_host'], config['snmp_port']) # Configure the transport target (IPv4 or IPv6). try: # Will raise an exception if ``snmp_host`` isn't an IPv6 address. ipaddress.IPv6Address(config['snmp_host']) transport_target = hlapi.Udp6TransportTarget(transport_addr) except ValueError: transport_target = hlapi.UdpTransportTarget(transport_addr) transport_target.retries = config['snmp_retries'] transport_target.timeout = config['snmp_timeout'] var_binds = hlapi.NotificationType(hlapi.ObjectIdentity(trap_data['oid'])) var_binds.addVarBinds( hlapi.ObjectType(hlapi.ObjectIdentity(oids['alertname']), hlapi.OctetString(trap_data['alertname'] or '')), hlapi.ObjectType(hlapi.ObjectIdentity(oids['status']), hlapi.OctetString(trap_data['status'] or '')), hlapi.ObjectType(hlapi.ObjectIdentity(oids['severity']), hlapi.OctetString(trap_data['severity'] or '')), hlapi.ObjectType(hlapi.ObjectIdentity(oids['instance']), hlapi.OctetString(trap_data['instance'] or '')), hlapi.ObjectType(hlapi.ObjectIdentity(oids['job']), hlapi.OctetString(trap_data['job'] or '')), hlapi.ObjectType(hlapi.ObjectIdentity(oids['description']), hlapi.OctetString(trap_data['description'] or '')), hlapi.ObjectType( hlapi.ObjectIdentity(oids['labels']), hlapi.OctetString(json.dumps(trap_data['labels'] or ''))), hlapi.ObjectType(hlapi.ObjectIdentity(oids['timestamp']), hlapi.TimeTicks(trap_data['timestamp'])), hlapi.ObjectType(hlapi.ObjectIdentity(oids['rawdata']), hlapi.OctetString(json.dumps(trap_data['rawdata'])))) error_indication, error_status, error_index, _ = next( hlapi.sendNotification( hlapi.SnmpEngine(), hlapi.CommunityData(config['snmp_community'], mpModel=1), transport_target, hlapi.ContextData(), 'trap', var_binds)) if error_indication: logger.error('SNMP trap not sent: %s', error_indication) elif error_status: logger.error('SNMP trap receiver returned error: %s @%s', error_status, error_index) else: logger.debug('Sending SNMP trap: %s', trap_data)