def update(self): try: # pass port = '4' index = '13' oid = netsnmp.Varbind('.1.3.6.1.4.1', '.2011.5.25.157.1.1.1.1.15.9', '2', 'INTEGER') # print netsnmp.snmpset(oid,Version=1,DestHost='10.15.9.253',Community='private@it') print netsnmp.snmpget('.1.3.6.1.4.1.2011.5.25.157.1.1.1.1.15.5', Version=1, DestHost='10.15.9.253', Community='private@it') print netsnmp.snmpgetnext( '.1.3.6.1.4.1.2011.5.25.157.1.1.1.1.15.5', Version=1, DestHost='10.15.9.253', Community='private@it') print netsnmp.snmpwalk('.1.3.6.1.4.1.2011.5.25.157.1.1.1.1.15', Version=1, DestHost='10.15.9.253', Community='private@it') except Exception, err: print err
def collect(self): oid = netsnmp.VarList(netsnmp.Varbind(self.conf['poller_conf']['table'])) netsnmp.snmpwalk(oid, DestHost=self.conf['hostname'], Version=self.conf['snmp_version'], Community=self.conf['snmp_community'], UseNumeric=True) tbl = {} for ret in oid: if ret.iid not in tbl: tbl[ret.iid] = {} tbl[ret.iid][ret.tag.split('.')[-1]] = ret.val tbl = sorted(tbl.items()) for idx in xrange(len(tbl)): key, val = tbl[idx] for obj in self.conf['items']: skp = False for flt in obj.get('filter', ':'): chk = flt.strip().split(':', 1) skp = skp or not re.match(chk[1], val.get(chk[0], '')) if skp: continue lbl = [val[i] if unicode(i).isnumeric() else i.format(index=idx, label=key) for i in obj['labels'].split('.')] self.data[self.escape(lbl)] = val[obj['values']]
def snmp(): parser = argparse.ArgumentParser() parser.add_argument("-v","--version",help="version 1 or 2 or 3",choices=[1,2,3],type=int) parser.add_argument("-ip","--ip",help="hostname/ip") parser.add_argument("-c","--community",help="communit name") parser.add_argument("-u","--v3_uname",help="v3 user name") parser.add_argument("-x","--privprotocol",help="v3 priv protocol ex:AES") parser.add_argument("-X","--privpassword",help="v3 priv password") parser.add_argument("-a","--authprotocol",help="v3 auth protocol") parser.add_argument("-A","--authpassword",help="v3 auth password") parser.add_argument("-l","--level",help="v3 level") parser.add_argument("-o","--oid",help="oid to get") try: args = parser.parse_args() except Exception: print "error in arguments passed" vars = netsnmp.VarList(netsnmp.Varbind(args.oid)) snmpwalk=[] if args.version==2 or args.version==1: netsnmp.snmpwalk(vars, Version=args.version, DestHost=args.ip,Community=args.community) for i in vars: print('{}.{} : {}'.format(i.tag, i.iid, i.val)) snmpwalk.append('{}.{} : {}'.format(i.tag, i.iid, i.val)) if args.version==3: netsnmp.snmpwalk(vars, Version=args.version, DestHost=args.ip, SecLevel=args.level,AuthProto=args.authprotocol, AuthPass=args.authpassword, PrivProto=args.privprotocol,PrivPass=args.privpassword, SecName=args.v3_uname) for j in vars: print('{}.{} : {}'.format(j.tag, j.iid, j.val)) snmpwalk.append('{}.{} : {}'.format(j.tag, j.iid, j.val)) return snmpwalk
def equipment_monitor_interface_list(request, interface): interfaces = [] id, sep , num = interface.partition("-") equipment = get_equipment(int(id)) interfaces_name = netsnmp.snmpwalk(ifDescr, Version = 2, DestHost = equipment.ip, Community = "newtouch") interfaces_status = netsnmp.snmpwalk(ifOperStatus, Version = 2, DestHost = equipment.ip, Community = "newtouch") for name in interfaces_name: interface = EquipmentMonitorInterFace(interfaces_name.index(name), name, interfaces_status[interfaces_name.index(name)], equipment.ip) interface.fill_snmp_data() interface.fill_interface_ip() interfaces.append(interface) return interfaces
def check_neighbor_status_v4(host,community): peers_v4 = {} asns_v4 = {} reasons_v4 = {} # Walk all peers from BGP-MIB oids_v4 = netsnmp.VarList( netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.3.1.4')) res_v4 = netsnmp.snmpwalk( oids_v4, Version = 2, DestHost = host, Community = community) # Due to SNMP deamon lagg in the router, when switching communities from one to the other, # sometimes we fail to get snmp. # If we wait 5 sec and try again it should work just fine if not res_v4: time.sleep(5) oids_v4 = netsnmp.VarList( netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.3.1.4')) res_v4 = netsnmp.snmpwalk( oids_v4, Version = 2, DestHost = host, Community = community) for oid_v4 in oids_v4: ipv4 = oid_v4.tag.replace("enterprises.9.9.187.1.2.5.1.3.1.4.", "") peers_v4[ipv4] = get_state(oid_v4.val) # Get RemoteAs from BGP-MIB asoid = netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.11.1.4.'+ipv4) asn = netsnmp.snmpget( asoid, Version = 2, DestHost = host, Community = community ) asns_v4[ipv4] = asn[0] # Get lastErrorTxt from BGP-MIB reasonoid = netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.28.1.4.'+ipv4) reason = netsnmp.snmpget( reasonoid, Version = 2, DestHost = host, Community = community ) reasons_v4[ipv4] = reason[0] return (peers_v4,asns_v4,reasons_v4)
def update(self): self.logger.info("Updating known mac addresses") switches = self.switch_collection.find() mac_count = 0 for switch in switches: obj_switch = Switch(id = switch['_id']) oid = obj_switch.get('oid') ip = obj_switch.get('ip') read = obj_switch.get('read') switch_id = obj_switch.id mongo_doc = {} mongo_doc['switch_id'] = switch_id try: self.logger.debug("Requesting following data: oid=%s\tip=%s\tcommunity=%s\tswitch_id=%s" % (oid, ip, read, switch_id)) varlist = netsnmp.VarList(netsnmp.Varbind(oid)) res = netsnmp.snmpwalk(varlist, Version = 1, DestHost = ip, Community = read) ifname_oid = '.1.3.6.1.2.1.31.1.1.1.1' # ifName self.logger.debug("Requesting following data: oid=%s\tip=%s\tcommunity=%s\tswitch_id=%s" % (ifname_oid, ip, read, switch_id)) varlist_ifnames = netsnmp.VarList(netsnmp.Varbind(ifname_oid)) res_ifnames = netsnmp.snmpwalk(varlist_ifnames, Version = 1, DestHost = ip, Community = read) updated = datetime.datetime.utcnow() portnums = {} for i in range(len(varlist_ifnames)): if bool(varlist_ifnames[i].iid): pornnum = varlist_ifnames[i].iid else: pornnum = varlist_ifnames[i].tag.split('.')[-1:][0] tmpvar = varlist_ifnames[i] try: portnums[int(pornnum)] = str(varlist_ifnames[i].val) except: pass for i in range(len(varlist)): mac = '' port = str(varlist[i].val) try: portname = portnums[int(varlist[i].val)] except KeyError: portname = port for elem in varlist[i].tag.split('.')[-6:]: mac += hex(int(elem)).split('x')[1].zfill(2) + ':' mac = mac[:-1].lower() mongo_doc['mac'] = mac mongo_doc['port'] = port mongo_doc['portname'] = portname mongo_doc_updated = mongo_doc.copy() mongo_doc_updated['updated'] = updated res = self.known_mac_collection.find_and_modify(mongo_doc, {'$set': mongo_doc_updated}, upsert = True) if not bool(res): mac_count += 1 except NameError: if self.logger: self.logger.error("Cannot reach '{}'".format(ip)) except: err = sys.exc_info()[0] if self.logger: self.logger.error(err) if mac_count > 0: self.logger.info("Was added {} new mac addresses.".format(mac_count)) return True
def GetSNMPValueTable(host, collector): """ Gets the SNMP values for Table MIBS """ if debug: print "GetSNMPValueTable for %s %s" % (host['DESC'], collector['DESC']) mibdesc = collector['MIBDESC'] mibdata = collector['MIBDATA'] community = host['COMMUNITY'] ipaddr = host['IPADDR'] now = int(time.time()) try: desc = snmpwalk(mibdesc, Version=2, DestHost=ipaddr, Community=community) vals = snmpwalk(mibdata, Version=2, DestHost=ipaddr, Community=community) results = [] for i in range(len(desc)): description = collector["NAMING_SCHEMA"].replace( '$HOST$', host['DESC']).replace('$COLLECTOR$', collector['DESC']).replace( '$MIB$', desc[i]) results.append([description, vals[i], now]) return results except: print "SNMP ISSUES with %s using %s" % (host['DESC'], collector['DESC']) return "NoData"
def make_route_table(ip): result = {} networks = netsnmp.snmpwalk( netsnmp.Varbind('ipRouteDest'), Version=2, DestHost=ip, Community=c) #snmpwalk -v 2c -c c t ipRouteDest masks = netsnmp.snmpwalk(netsnmp.Varbind('ipRouteMask'), Version=2, DestHost=ip, Community=c) #snmpmask -v 2c -c c t ipRouteMask next_hops = netsnmp.snmpwalk( netsnmp.Varbind('ipRouteNextHop'), Version=2, DestHost=ip, Community=c) #snmpwalk -v 2c -c c t ipRouteNextHop types = netsnmp.snmpwalk(netsnmp.Varbind('ipRouteType'), Version=2, DestHost=ip, Community=c) #snmpwalk -v 2c -c c t ipRouteType protos = netsnmp.snmpwalk(netsnmp.Varbind('ipRouteProto'), Version=2, DestHost=ip, Community=c) #snmpwalk -v 2c -c c t ipRouteProto for x in xrange(len(networks)): result[networks[x]] = (route(network=networks[x], mask=masks[x], next_hop=next_hops[x], type=types[x], proto=protos[x])) return result
def get_status_table(remote_ip, community): status_table = {} # descriptions ifdesc_oid = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.2.1.2.2.1.2')) logging.debug('Walking if descriptions -- ') netsnmp.snmpwalk(ifdesc_oid, DestHost=remote_ip, Version=1, Community=community) if not ifdesc_oid: plugin_exit(CRITICAL, 'Unable to retrieve SNMP interface descriptions') for member in ifdesc_oid: logging.debug('Interface info: {0}'.format(member.print_str())) a = {'name': member.val, 'index': member.iid} status_table[a['index']] = a # status ifstatus_oid = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.2.1.2.2.1.8')) logging.debug('Walking if status -- ') netsnmp.snmpwalk(ifstatus_oid, DestHost=remote_ip, Version=1, Community=community) if not ifstatus_oid: plugin_exit(CRITICAL, 'Unable to retrieve SNMP interface status') for member in ifstatus_oid: logging.debug('Interface status info: {0}'.format(member.print_str())) a = {'status': member.val, 'index': member.iid} status_table[a['index']]['status'] = a['status'] return status_table
def get_netgear_mac_table(hostname): """Returns [(port, mac_addr), ...].""" macs = netsnmp.snmpwalk('.1.3.6.1.2.1.17.4.3.1.1', Version=2, Community=netgear_community, DestHost=hostname) ports = netsnmp.snmpwalk('.1.3.6.1.2.1.17.4.3.1.2', Version=2, Community=netgear_community, DestHost=hostname) return zip(map(int, ports), map(format_mac, macs))
def get_netgear_port_traffic(hostname): """Returns [(port, octets_rcvd, octets_sent), ...].""" rcvd = netsnmp.snmpwalk('.1.3.6.1.2.1.2.2.1.10', Version=2, Community=netgear_community, DestHost=hostname) sent = netsnmp.snmpwalk('.1.3.6.1.2.1.2.2.1.16', Version=2, Community=netgear_community, DestHost=hostname) return zip(range(1, 49), [map(int, k) for k in zip(rcvd, sent)])
def get_cisco_routing_table(): """Returns [(mac_addr, ip_addr), ...].""" macs = netsnmp.snmpwalk('.1.3.6.1.2.1.3.1.1.2.51.1', Version = 1, Community = 'public', DestHost = cisco_ip) ips = netsnmp.snmpwalk('.1.3.6.1.2.1.4.22.1.3.51', Version = 1, Community = 'public', DestHost = cisco_ip) return zip(map(format_mac, macs), ips)
def get_netgear_port_traffic(hostname): """Returns [(port, octets_rcvd, octets_sent), ...].""" rcvd = netsnmp.snmpwalk('.1.3.6.1.2.1.2.2.1.10', Version = 2, Community = netgear_community, DestHost = hostname) sent = netsnmp.snmpwalk('.1.3.6.1.2.1.2.2.1.16', Version = 2, Community = netgear_community, DestHost = hostname) return zip(range(1,49), [map(int, k) for k in zip(rcvd, sent)])
def get_cisco_routing_table(): """Returns [(mac_addr, ip_addr), ...].""" macs = netsnmp.snmpwalk('.1.3.6.1.2.1.3.1.1.2.51.1', Version=1, Community='public', DestHost=cisco_ip) ips = netsnmp.snmpwalk('.1.3.6.1.2.1.4.22.1.3.51', Version=1, Community='public', DestHost=cisco_ip) return zip(map(format_mac, macs), ips)
def get_netgear_mac_table(hostname): """Returns [(port, mac_addr), ...].""" macs = netsnmp.snmpwalk('.1.3.6.1.2.1.17.4.3.1.1', Version = 2, Community = netgear_community, DestHost = hostname) ports = netsnmp.snmpwalk('.1.3.6.1.2.1.17.4.3.1.2', Version = 2, Community = netgear_community, DestHost = hostname) return zip(map(int, ports), map(format_mac, macs))
def main(): streams = OrderedDict({}) #streams = {} try: FILE = open(filename,'r') streams= pickle.load(FILE) print "Loaded File" print streams except: "No File, creating" print "Streams Read" hosts = ['192.168.11.200','192.168.11.1', '192.168.11.201'] snmpTypes = ['ifInOctets','ifOutOctets','ifInUcastPkts','ifOutUcastPkts'] for hostname in hosts: snmpHost = {'Community': 'public', 'DestHost': hostname, 'Version': 2} oid = netsnmp.VarList(netsnmp.Varbind('ifTable')) netsnmp.snmpwalk(oid,**snmpHost) ifNames = {} for o in oid: if(o.tag == "ifDescr"): ifNames[o.iid] = o.val if(o.tag in snmpTypes): s =Stream(oid="%s.%s"%(o.tag,o.iid), iid=o.iid, tag=o.tag, value=int(o.val), host=hostname, ifName=ifNames[o.iid]) s.save(streams) #createStreams(streams) #print STREAMS results = processStreams(streams) print results postResults(results) try: FILE.close() except: pass f = open(filename,'w') pickle.dump(streams,f) f.close()
def get_net_equipment_snmpmsg(host, commit): snmpmsg = SnmpMessage() snmpmsg.cpu = netsnmp.snmpwalk(hh3cEntityExtCpuUsage, Version = 2, DestHost = host, Community = commit) snmpmsg.mem = netsnmp.snmpwalk(hh3cEntityExtMemUsage, Version = 2, DestHost = host, Community = commit) return snmpmsg
def fill_interface_ip(self): ip_index = netsnmp.snmpwalk(ipAdEntIndex, Version = 2, DestHost = self.equipment_ip, Community = "newtouch") if str(self.id + 1) in ip_index: self.ip = netsnmp.snmpwalk(ipAdEntAddr, Version = 2, DestHost = self.equipment_ip, Community = "newtouch")[ip_index.index(str(self.id + 1))] else: self.ip = "-"
def snmp_walk(host, credential, *args, **kwargs): """Impelmentation of snmpwalk functionality :param host: switch ip :param credential: credential to access switch :param args: OIDs :param kwargs: key-value pairs """ try: import netsnmp except ImportError: logging.error("Module 'netsnmp' do not exist! Please install it first") return None if 'version' not in credential or 'community' not in credential: logging.error("[utils] missing 'version' and 'community' in %s", credential) return None version = None if credential['version'] in AUTH_VERSIONS: version = AUTH_VERSIONS[credential['version']] varbind_list = [] for arg in args: varbind = netsnmp.Varbind(arg) varbind_list.append(varbind) var_list = netsnmp.VarList(*varbind_list) netsnmp.snmpwalk(var_list, DestHost=host, Version=version, Community=credential['community'], **kwargs) result = [] if not var_list: logging.error("[hsdiscovery][utils][snmp_walk] retrived no record!") return result for var in var_list: response = {} response['elem_name'] = var.tag response['iid'] = var.iid response['value'] = var.val response['type'] = var.type result.append(response) return result
def snmp_get(oid = None, ver = '2', dst = None, community = 'public'): oid =netsnmp.Varbind('sysDescr') result = netsnmp.snmpwalk(oid = oid, Version = ver, DestHost=dst, communityy = community) return result
def __SNMPWALK_netsnmp(self, oid, exitonerror=True): if not self.__prepared_snmp: self.prepare_snmp() if oid in self.__SNMP_Cache: self.verbose(2, "%40s -> (CACHED) %s" % (oid, self.__SNMP_Cache[oid])) return self.__SNMP_Cache[oid] result = netsnmp.snmpwalk(oid, Version=int(self.options.snmpversion), DestHost=self.options.host, Community=self.options.snmpauth) if not result: if exitonerror: self.back2nagios( 3, 'Timeout or no answer from "%s" looking for "%s"' % (self.options.host, oid)) else: return None self.__SNMP_Cache[oid] = result self.verbose(2, "%40s -> %s" % (oid, result)) return result
def snmp_test(): var = netsnmp.Varbind(".1.3.6.1.4.1.19536.10.1.4.7.1.2") res = netsnmp.snmpwalk(var, Version=1, DestHost='192.168.1.101', Community='public') print(res)
def get_snmp_info(): timestr = str(datetime.datetime.now()).split('.')[0] sysName_oid = netsnmp.Varbind("sysName") #系统名称 location_oid = netsnmp.Varbind("sysLocation") #物理位置 sysContact_oid = netsnmp.Varbind("sysContact") #联系人信息 ip_list = get_ip_list() for i in ip_list: result = netsnmp.snmpwalk(location_oid, sysContact_oid, sysName_oid, Version=2, DestHost='{0}'.format(i), Community='Community', Timeout=1000000) if result: sysName = result[0] sysContact = result[2] else: sysName = '' sysContact = '' try: insert_mysql(i, sysName, sysContact, timestr) except Exception as e: print e.args print i + '\t' + str(sysName) + '\t' + str(sysContact)
def snmp_walk(self, widget): try: import netsnmp except: self.log( '[D2] Module netsnmp not present. You can download and install this module at this url: http://www.net-snmp.org/wiki/index.php/Python_Bindings' ) return community = oid = version = '' self.c = self.wTree2.get_widget("community") community = self.c.get_text() self.c = self.wTree2.get_widget("version") version = self.c.get_value_as_int() self.c = self.wTree2.get_widget("oid") oid = self.c.get_text() self.c = self.wTree2.get_widget("snmpinfo") self.buffer = self.c.get_buffer() vars = netsnmp.VarList(netsnmp.Varbind(oid)) res = netsnmp.snmpwalk(vars, Version=version, DestHost=self.host, Community=community) nfo = '' for var in vars: nfo += "ifIndex value = %s\tifDescr value = %s\n" % (var.iid, var.val) self.buffer.set_text(nfo)
def ifindex_re(): oid_jnxOperatingState_RE = ".1.3.6.1.4.1.2636.3.1.13.1.6.9" result_ifindex_re = netsnmp.snmpwalk(netsnmp.Varbind(oid_jnxOperatingState_RE), **args) if len(result_ifindex_re) > 1: return result_ifindex_re else: return tuple(result_ifindex_re[0])
def getconsumableslevels(host, community): consumables_number = len( netsnmp.snmpwalk(netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.6.1"), Version=1, DestHost=host, Community=community)) res = dict() for i in range(1, consumables_number + 1): res[i] = dict() res[i]['name'] = netsnmp.snmpget( netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.6.1." + str(i)), Version=1, DestHost=host, Community=community)[0] res[i]['level'] = netsnmp.snmpget( netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.9.1." + str(i)), Version=1, DestHost=host, Community=community)[0] return res
def check_pan_disk(hostname, community): pan_disk_oid = '.1.3.6.1.2.1.25.2.3.1' oid = netsnmp.Varbind(pan_disk_oid) #logger.debug('oid %s',oid) output = netsnmp.snmpwalk(oid, Version=2, DestHost=hostname, Community=community) #logger.debug('output %s',output) # return output #def calc_pan_disk(): [index, oid, descr, allocUt, AvailS, UsedS] = [output[i:i+11] for i in range(0,len(output),11)] disk_info= descr[0:5]+AvailS[0:5]+UsedS[0:5] [Disktype, AvailSize, UsedSize] =[disk_info[i:i+5] for i in range(0,len(disk_info),5)] #List for all types of Disk on the pans ram = Disktype[0],AvailSize[0],UsedSize[0] sd = Disktype[1],AvailSize[1],UsedSize[1] cfg_dk = Disktype[2],AvailSize[2],UsedSize[2] lg_dk = Disktype[3],AvailSize[3],UsedSize[3] rt_dk = Disktype[4],AvailSize[4],UsedSize[4] #print ram #print sd #print cfg_dk #print lg_dk #print rt_dk #Zipping all lists together disks= zip(ram, sd, cfg_dk, lg_dk, rt_dk) #print disks #flatten the list dk_flat = [val for sublist in disks for val in sublist] #print dk_flat #Slicing lists to create key value pairs for dictionary disk_keys = dk_flat[0:5] disk_av_values = dk_flat[5:10] disk_used_values = dk_flat[10:15] #print disk_keys #print disk_av_values #print disk_used_values #Creating a dictionary d = dict(zip(disk_keys,zip(disk_av_values,disk_used_values))) pprint (d) # percentange calculation for key in d: #d2 = {key: (v1,v2,((int(v2)/int(v1))*100)) for key,(v1,v2) in d.items()} #print d2 perc_usage = float( float(d[key][1])/float(d[key][0]))*100 # print key, usage if perc_usage > 30.0: alert_level = 'CRITICAL' print "Disk name" + " " + key + " " + "is using more than 30%" elif perc_usage > 10.0: alert_level = 'WARNING' print "Disk name" + " " + key + " " + "is using more than 10%" else: alert_level = 'OK'
def query(self): """ snmpwalk """ result = None try: result = netsnmp.snmpwalk(netsnmp.VarList( netsnmp.Varbind(self.oid, '', 10, 'INTEGER')), Version=int(self.version), DestHost=self.destHost, Community=self.community) print result if len(result) == 0: error = 'snmp get lldp info fail' if not os.path.exists(self.file): os.mknod(self.file) with open(self.file, 'w') as f: csvwriter = csv.writer(f) csvwriter.writerow( [self.destHost, self.community, self.oid, error]) except Exception: error = 'snmp get lldp info fail' if not os.path.exists(self.file): os.mknod(self.file) with open(self.file, 'w') as f: csvwriter = csv.writer(f) csvwriter.writerow( [self.destHost, self.community, self.oid, error]) result = None return result
def query(self): """Creates SNMP query session""" try: result = netsnmp.snmpwalk(self.oid, Version=self.version, DestHost=self.destHost, Community=self.community) except Exception, err: print err result = None
def snmp_walk(self,iod): var=netsnmp.Varbind(iod) result = netsnmp.snmpwalk(var, Version = self.Version, DestHost = self.DestHost, Community = self.Community) return result
def getOIDsButton_clicked(self): if(self.lineEditIP.text() <> ""): ip = str(self.lineEditOID.text()) vars = netsnmp.VarList( netsnmp.Varbind('ifDescr')) res = netsnmp.snmpwalk( vars, Version = 1, DestHost = ip, Community = 'public' ) print res else: print "IP Required!"
def getServiceTag(hst,com): oid = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.4.1.674.10892.1.300.10.1.11')) res = netsnmp.snmpwalk(oid, Version = 2, DestHost=hst, Community=com) if str(res) != "()": return res else: print "Couldn't read snmp value" sys.exit(3)
def snmpGet(host): #session = netsnmp.Session(Version=2, DestHost=host, Community=snmp_community) args = {"Version": 2, "DestHost": host, "Community": snmp_community} try: a_file = open(workingDirectory + "/" + host + ".pkl", "rb") lastSample = pickle.load(a_file) except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) print "Warning! No last sample detected" lastSample = None newSample = dict() for idx in netsnmp.snmpwalk(netsnmp.Varbind("IF-MIB::ifIndex"), **args): ifname, oper, cin, cout, ifspeed = netsnmp.snmpget( netsnmp.Varbind("IF-MIB::ifName", idx), netsnmp.Varbind("IF-MIB::ifOperStatus", idx), netsnmp.Varbind("IF-MIB::ifHCInOctets", idx), netsnmp.Varbind("IF-MIB::ifHCOutOctets", idx), netsnmp.Varbind("IF-MIB::ifSpeed", idx), **args) assert (ifname is not None and cin is not None and cout is not None) #Skip internal interfaces if ifname == "Internal-Data0/1" or ifname == "diagnostic" or ifname == "nlp_int_tap" or ifname == "ccl_ha_nlp_int_tap" or ifname == "ha_ctl_nlp_int_tap" or ifname == "failover": continue # Only look at interfaces that are up if oper != "1": continue newSample[ifname] = {'cin': cin, 'cout': cout, 'ts': time.time()} if (lastSample is not None): # Formula: https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/8141-calculate-bandwidth-snmp.html deltaSeconds = int(newSample[ifname]['ts']) - int( lastSample[ifname]['ts']) deltaIn = int(newSample[ifname]['cin']) - int( lastSample[ifname]['cin']) deltaOut = int(newSample[ifname]['cout']) - int( lastSample[ifname]['cout']) utilizationIn = (float(deltaIn) * 8) / ( float(deltaSeconds) * 1024 * 1024) # Mbps utilizationOut = (float(deltaOut) * 8) / ( float(deltaSeconds) * 1024 * 1024) #Mbps #print("{} utz in: {} utz out: {}".format( ifname, utilizationIn, utilizationOut)) fp = open(output_path + host + "-interfaces.csv", "a+") now = datetime.datetime.now() log = "{},{},{},{}".format(now, ifname, utilizationIn, utilizationOut) fp.write(log + '\n') fp.close() else: print("Warning! No last sample detected - skipping") a_file = open(workingDirectory + "/" + host + ".pkl", "wb") pickle.dump(newSample, a_file) a_file.close()
def walk(self, oid): """ Ejecuta el equivalente a un 'snmpwalk' con los parametros establecidos """ try: result = netsnmp.snmpwalk(oid, Version=self.version, DestHost=self.desthost, SecName=self.username, Community=self.community, Timeout=self.timeout) return result except Exception as e: print type(e)
def getServiceTag(hst, com): oid = netsnmp.VarList( netsnmp.Varbind('.1.3.6.1.4.1.674.10892.1.300.10.1.11')) res = netsnmp.snmpwalk(oid, Version=2, DestHost=hst, Community=com) if str(res) != "()": return res else: print "Couldn't read snmp value" sys.exit(3)
def snmp_query(self): try: result = netsnmp.snmpwalk(self.oid_set, Version=self.version, DestHost=self.destHost, Community=self.community) except Exception, err: print err result = None
def walk_data(host, version, community, oid): var = netsnmp.Varbind(oid) try: data = netsnmp.snmpwalk(var, Version=version, DestHost=host, Community=community) except: helper.exit(summary="\n SNMP connection to device failed " + oid, exit_code=unknown, perfdata='') if not data: helper.exit(summary="\n SNMP connection to device failed " + oid, exit_code=unknown, perfdata='') return data
def get_list_ap_names(desthost, snmp_community): var = netsnmp.Varbind(index_ap_name) res = netsnmp.snmpwalk(var, Version=2, DestHost=desthost, Community=snmp_community) list_ap_names = [] for name in res: list_ap_names.append(name) return list_ap_names
def query(self): """ Creates SNMP query session """ try: result = netsnmp.snmpwalk(self.oid, Version=self.version, DestHost=self.destHost, Community=self.community) except Exception, err: print err result = None
def SNMPSERVER(ID,IP,Community,port): #Apache server snmp monitoring here oid=netsnmp.Varbind('.1.3.6.1.4.1.8072.1.3.1.4.1.2.6.97.112.97.99.104.101') IP=IP+":"+str(port) val=netsnmp.snmpwalk(oid, Version = 1, DestHost="%s" %IP, Community="%s" %Community ) if len(val)==4: l=os.system('rrdtool update {0}.rrd N:{1}:{2}:{3}:{4} '.format(ID,val[0],val[1],val[2],val[3])) if l!=0:#rrd condition os.system('rrdtool create {0}.rrd --step 60 DS:CPUusage:GAUGE:120:U:U DS:reqpersec:GAUGE:120:U:U DS:bytespersec:GAUGE:120:U:U DS:bytesperreq:GAUGE:120:U:U RRA:AVERAGE:0.5:1:1440 '.format(ID)) os.system('rrdtool update {0}.rrd N:{1}:{2}:{3}:{4} '.format(ID,val[0],val[1],val[2],val[3])) print ID,IP,val[0],val[1],val[2],val[3]
def get_number_clients_ap(ap_name, desthost, snmp_community): tag = get_tag_ap(ap_name, desthost, snmp_community) oid = re.split(pattern, tag) full_oid = index_ap_clients + oid[1] req = netsnmp.snmpwalk(full_oid, Version=2, DestHost=desthost, Community=snmp_community) req = map(int, req) return sum(req)
def getOIDsButton_clicked(self): if (self.lineEditIP.text() <> ""): ip = str(self.lineEditOID.text()) vars = netsnmp.VarList(netsnmp.Varbind('ifDescr')) res = netsnmp.snmpwalk(vars, Version=1, DestHost=ip, Community='public') print res else: print "IP Required!"
def check_neighbor_status_v6(host,community): peers_v6 = {} asns_v6 = {} reasons_v6= {} # Walk all peers from BGP-MIB oids_v6 = netsnmp.VarList( netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.3.2.16')) res_v6 = netsnmp.snmpwalk( oids_v6, Version = 2, DestHost = host, Community = community ) for oid_v6 in oids_v6: ipv6 = oid_v6.tag.split('.') oid = oid_v6.tag # Convert into hexadecimal, each variable 16 bytes long a = ipv6_converter(ipv6[11]) +ipv6_converter(ipv6[12]) b = ipv6_converter(ipv6[13]) +ipv6_converter(ipv6[14]) c = ipv6_converter(ipv6[15]) +ipv6_converter(ipv6[16]) d = ipv6_converter(ipv6[17]) +ipv6_converter(ipv6[18]) e = ipv6_converter(ipv6[19]) +ipv6_converter(ipv6[20]) f = ipv6_converter(ipv6[21]) +ipv6_converter(ipv6[22]) g = ipv6_converter(ipv6[23]) +ipv6_converter(ipv6[24]) h = ipv6_converter(ipv6[25]) +ipv6_converter(ipv6[26]) # Remove leading zeroes a = a.lstrip("0") b = b.lstrip("0") c = c.lstrip("0") d = d.lstrip("0") e = e.lstrip("0") f = f.lstrip("0") g = g.lstrip("0") h = h.lstrip("0") # Contstruct properly formatted IPv6 address ipv6 = a +':' +b +':' +c +':' +d +':' +e +':' +f +':' +g ipv6 = ipv6.rstrip(":") ipv6 = ipv6 +'::' +h peers_v6[ipv6] = get_state(oid_v6.val) # Get RemoteAs from BGP-MIB oid = oid.replace("enterprises.9.9.187.1.2.5.1.3.2.16.", "enterprises.9.9.187.1.2.5.1.11.2.16.") asoid = netsnmp.Varbind(oid) asn = netsnmp.snmpget( asoid, Version = 2, DestHost = host, Community = community ) asns_v6[ipv6] = asn[0] # Get lastErrorTxt from BGP-MIB oid = oid.replace("enterprises.9.9.187.1.2.5.1.11.2.16.", "enterprises.9.9.187.1.2.5.1.28.2.16.") reasonoid = netsnmp.Varbind(oid) reason = netsnmp.snmpget( reasonoid, Version = 2, DestHost = host, Community = community ) reasons_v6[ipv6] = reason[0] return (peers_v6,asns_v6,reasons_v6)
def GetSNMPValue(host, community, mib, desc): """ Gets the SNMP value for a given mib """ if debug: print "GetSNMPVal for %s %s" % (host, desc) now = int(time.time()) try: value = snmpwalk(mib, Version=2, DestHost=host, Community=community)[0] return [desc, value, now] except: print "SNMP ISSUES with %s using %s" % (host, desc) return "NoData"
def SNMPWALK(oid): VBoid = netsnmp.Varbind(oid) result = netsnmp.snmpwalk(oid, Version = int(options.version), DestHost=options.host, Community=options.community) if result == None: back2nagios(RETURNCODE['UNKNOWN'], 'SNMP UNKNOWN: Timeout or no answer from %s' % options.host) if options.verb >= 1: print "%40s -> %s" % (oid, result) return result
def get_cluster_discovery(oid): name = netsnmp.Varbind(oid) result = netsnmp.snmpwalk(name, Version=version, DestHost=hostname, Community=community, SecName=snmpv3_user, SecLevel=snmpv3_level, AuthProto=snmpv3_auth, AuthPass=snmpv3_auth_pass) nameList = list(result) return nameList
def get_snmp_metric(self, bucket, host, version, oid, community): logger.debug("Sending oid request to snmp : %s" % oid) try: snmp_oid = netsnmp.Varbind(oid) metric = netsnmp.snmpwalk(snmp_oid, Version = version, DestHost = host, Community = community)[0] except IndexError: metric = netsnmp.snmpget(snmp_oid, Version = version, DestHost = host, Community = community)[0] except: logger.error(sys.exc_info()) metric = 0 return metric
def fill_snmp_data(self): self.inoctets = netsnmp.snmpwalk(ifInOctets, Version = 2, DestHost = self.equipment_ip, Community = "newtouch")[self.id] self.outoctets = netsnmp.snmpwalk(ifOutOctets, Version = 2, DestHost = self.equipment_ip, Community = "newtouch")[self.id] self.indiscards = netsnmp.snmpwalk(ifInDiscards, Version = 2, DestHost = self.equipment_ip, Community = "newtouch")[self.id] self.outdiscards = netsnmp.snmpwalk(ifOutDiscards, Version = 2, DestHost = self.equipment_ip, Community = "newtouch")[self.id] self.inerrors = netsnmp.snmpwalk(ifInErrors, Version = 2, DestHost = self.equipment_ip, Community = "newtouch")[self.id] self.outerrors = netsnmp.snmpwalk(ifOutErrors, Version = 2, DestHost = self.equipment_ip, Community = "newtouch")[self.id]
def fill_snmp_data(self): self.temperature = netsnmp.snmpwalk(hh3cEntityExtTemperature, Version = 2, DestHost = self.ip, Community = "newtouch")[2] + ' C' self.cpu_usage = netsnmp.snmpwalk(hh3cEntityExtCpuUsage, Version = 2, DestHost = self.ip, Community = "newtouch")[2] + "%" self.mem_usage = netsnmp.snmpwalk(hh3cEntityExtMemUsage, Version = 2, DestHost = self.ip, Community = "newtouch")[2] + "%" self.max_connect_num = netsnmp.snmpwalk(hh3cFWMaxConnNum, Version = 2, DestHost = self.ip, Community = "newtouch")[0] self.cur_connect_num = netsnmp.snmpwalk(hh3cFWConnNumCurr, Version = 2, DestHost = self.ip, Community = "newtouch")[0] self.interface_num = netsnmp.snmpwalk(ifNumber, Version = 2, DestHost = self.ip, Community = "newtouch")[0]
def query(self, oid): """ snmpwalk """ try: result = netsnmp.snmpwalk(oid, Version=self.version, DestHost=self.destHost, Community=self.community) except Exception as err: print(err) result = None return result
def query(self): """Creates SNMP query session""" try: result = netsnmp.snmpwalk(self.oid, Version = self.Version, DestHost = self.DestHost, Community = self.Community) except: #Note this is toy code, but let's us know what exception is raised import sys print sys.exc_info() result = None return result
def getconsumableslevels(host, community): consumables_number = len(netsnmp.snmpwalk(netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.6.1"), Version = 1, DestHost=host, Community=community)) res = dict() for i in range(1, consumables_number + 1): res[i] = dict() res[i]['name'] = netsnmp.snmpget(netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.6.1." + str(i)), Version = 1, DestHost=host, Community=community)[0] res[i]['level'] = netsnmp.snmpget(netsnmp.Varbind(".1.3.6.1.2.1.43.11.1.1.9.1." + str(i)), Version = 1, DestHost=host, Community=community)[0] return res
def query(self): 'Creates SNMP query session' try: result = netsnmp.snmpwalk(self.oid, Version = self.Version, DestHost = self.DestHost, Community = self.Community) except: import sys print sys.exc_info() result = None return result
def query(self): """Creates SNMP query session""" try: result = netsnmp.snmpwalk(self.oid, Version=self.Version, DestHost=self.DestHost, Community=self.Community) except: import sys print sys.exc_info() result = None return result
def get_stack_info(remote_ip, community): member_table = {} stack_table_oid = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.4.1.9.9.500.1.2.1.1.1')) logging.debug('Walking stack table -- ') netsnmp.snmpwalk(stack_table_oid, DestHost=remote_ip, Version=1, Community=community) if not stack_table_oid: plugin_exit(CRITICAL, 'Unable to retrieve SNMP stack table') for member in stack_table_oid: logging.debug('Member info: {0}'.format(member.print_str())) a = {'number': member.val, 'index': member.tag.rsplit('.').pop()} member_table[a['index']] = a stack_status_oid = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.4.1.9.9.500.1.2.1.1.6')) logging.debug('Walking stack status -- ') netsnmp.snmpwalk(stack_status_oid, DestHost=remote_ip, Version=1, Community=community) if not stack_status_oid: plugin_exit(CRITICAL, 'Unable to retrieve SNMP stack status') for member in stack_status_oid: logging.debug('Member info: {0}'.format(member.print_str())) index = member.tag.rsplit('.').pop() member_table[index]['status_num'] = member.val member_table[index]['status'] = stack_state(member.val) logging.debug('Stack info table to return: {0}'.format(member_table)) return member_table
def get_status_table(remote_ip, community): status_table = {} # descriptions ifdesc_oid = netsnmp.VarList(netsnmp.Varbind(".1.3.6.1.2.1.2.2.1.2")) logging.debug("Walking if descriptions -- ") netsnmp.snmpwalk(ifdesc_oid, DestHost=remote_ip, Version=1, Community=community) if not ifdesc_oid: plugin_exit(CRITICAL, "Unable to retrieve SNMP interface descriptions") for member in ifdesc_oid: logging.debug("Interface info: {0}".format(member.print_str())) a = {"name": member.val, "index": member.iid} status_table[a["index"]] = a # status ifstatus_oid = netsnmp.VarList(netsnmp.Varbind(".1.3.6.1.2.1.2.2.1.8")) logging.debug("Walking if status -- ") netsnmp.snmpwalk(ifstatus_oid, DestHost=remote_ip, Version=1, Community=community) if not ifstatus_oid: plugin_exit(CRITICAL, "Unable to retrieve SNMP interface status") for member in ifstatus_oid: logging.debug("Interface status info: {0}".format(member.print_str())) a = {"status": member.val, "index": member.iid} status_table[a["index"]]["status"] = a["status"] return status_table