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 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 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_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 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_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 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 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 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 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 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)
def get(oid, host, port=161, community='public', timeout=0, retries=0, rf=str, snmp_ver=2, walk=False): """ Args: oid: SNMP OID or MIB name host: target host port: target port (default: 161) community: SNMP community (default: public) timeout: max SNMP timeout retries: max retry count (default: 0) rf: return format: str, float, int or None snmp_ver: SNMP version (default: 2) walk: if True, SNMP walk will be performed Returns: If rf is set to None, raw pysnmp object is returned, otherwise parsed to float, int or str If walk is requested, list of pysnmp objects is returned """ result = [] snmpfunc = snmp_engine.nextCmd if walk else snmp_engine.getCmd try: for (err_i, err_st, err_idx, vals) in snmpfunc( 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)), lexicographicMode=False): if err_i or err_st: logging.debug('snmp error: %s' % err_i) return else: for v in vals: if walk: result.append(v) else: if rf is None: return v try: _v = str(v[1]) try: if rf is float: _v = float(_v) if rf is int: _v = int(_v) except: _v = None return _v except: return return result except: log_traceback() return
def _snmpPoke(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 taskSnmpGet(oid, host, port, readcommunity, getTable=False): # sample oid for table # oid=".1.3.6.1.2.1.4.20" if oid[0] == '.': oid = oid[1:] res = {} reqFunction = snmp.nextCmd if getTable else snmp.getCmd req = reqFunction(snmp.SnmpEngine(), snmp.CommunityData(readcommunity), snmp.UdpTransportTarget((host, port)), snmp.ContextData(), snmp.ObjectType(snmp.ObjectIdentity(oid))) while True: 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] value = _snmpFormatValue(varBind[1]) if not getTable: return value curOid = str(varBind[0]) # curOid like 1.3.6.1.2.1.4.20.1.2.127.0.0.1 # where 1.3.6.1.2.1.4.20 - main (table) oid # 1 - column index (usually starts from 1, but can differ) # 2 - row index (usually starts from 1, but can differ) # 127.0.0.1 - index row value # load first entry from table oid entryIndex = 1 prefix = oid + '.' + str(entryIndex) + "." if not curOid.startswith(prefix): break curOid = curOid[len(prefix):] # now curOid like 2.127.0.0.1 splitted = curOid.split('.') # sometimes colindex can skip some cols: 1,2, 4,5,6 colIndex = int(splitted[0]) # index value = row index + index row value # sometimes inde row value is empty - so use only row value indexValue = '.'.join(splitted[1:]) if indexValue not in res.keys(): res[indexValue] = [] rowValuesList = res[indexValue] oldLen = len(rowValuesList) if colIndex < oldLen: raise Exception("Unknown SNMP table error") if colIndex > oldLen: # extend array if colindex had skipped values rowValuesList += [None for nothing in range(colIndex - oldLen)] rowValuesList += [value] else: # error example (RequestTimedOut('No SNMP response received before # timeout',), 0, 0, []) raise Exception(str(reply[0])) # print(res) return res
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