def main(argv): parser = argparse.ArgumentParser(description='Insert ARPs into a database') parser.add_argument('-H', action="store", dest="hostname") parser.add_argument('-c', action="store", dest="comstring") results = parser.parse_args(argv) m = M(host=results.hostname, community="public", version=2) macs = m.ipNetToMediaPhysAddress ifdescr = m.ifDescr ifalias = m.ifAlias global add_mac add_mac = ("INSERT INTO arplist" "(routerip, portindex, alias, description, arpip, arpmac)" " VALUES (%s, %s, %s, %s, %s, %s)") global cnx cnx = mysql.connector.connect(user='******', password='******', host='mysql01.example.net', database='arpentries', buffered=True) for (index, value) in macs: try: macentry = m.ipNetToMediaPhysAddress[index, value] asciimac = binascii.hexlify(macentry) insertRow(results.hostname, int(index), str(ifalias[index]), str(ifdescr[index]), str(value), asciimac) except Exception: print "uh oh something went wrong" cnx.close()
def data(self, data=None): for i in self.mibs.split(","): load(i) self.manager = M(self.ip, self.community, self.version) m = self.manager d = {} d['model'] = str(self.manager.upsIdentModel).strip() d['manufacturer'] = str(m.upsIdentManufacturer).strip() d['values'] = {} d['values']['battery_voltage'] = int(m.upsBatteryVoltage) d['values']['battery_current'] = int(m.upsBatteryCurrent) d['values']['input_frequency'] = [] for l in m.upsInputFrequency: d['values']['input_frequency'].append(int(m.upsInputFrequency[l])) d['values']['input_voltage'] = [] for l in m.upsInputVoltage: d['values']['input_voltage'].append(int(m.upsInputVoltage[l])) d['values']['output_current'] = [] for l in m.upsOutputCurrent: d['values']['output_current'].append(int(m.upsOutputCurrent[l])) d['values']['output_power'] = [] for l in m.upsOutputPower: d['values']['output_power'].append(int(m.upsOutputPower[l])) return d
def has_snmp(self): load("SNMPv2-MIB") self.snmp = False try: m = M(host=str(self.host), community=str(self.snmp_group), version=2, timeout=2) if m.sysName is not None: self.snmp = True except Exception, e: self.has_error("(snmp) " + e.message) self.snmp = False
def Connect2Network(nethost): m = M(host=nethost, version=3, secname="SNMPUser", authprotocol="MD5", authpassword="******", privprotocol="DES", privpassword="******") return m
def set_memStat(self): """ Return mem infos """ m = M(host=self.snmpTarget, community=self.snmpCommunity, none=True) logging.debug("loading memory infos [5/x]...") self._mem_Free.append(int(m.ciscoMemoryPoolFree[1])) self._mem_Used.append(int(m.ciscoMemoryPoolUsed[1])) self._mem_Alloc.append(int(m.ciscoMemoryPoolLargestFree[1]))
def handle(self, *args, **options): # BGP4-MIB is IPv4-only. For IPv6, there are: # * draft-ietf-idr-bgp4-mibv2-15 (IETF, but expired) # * BGP4-V2-MIB-JUNIPER (Juniper) # * BGP4V2-MIB (Foundry/Brocade) # * CISCO-BGP4-MIB (Cisco) # * ARISTA-BGP4V2-MIB (Arista) # * FORCE10-BGP4-V2-MIB (Force10) # # Juniper was found to be buggy, and needs: # set protocols bgp snmp-options emit-inet-address-length-in-oid # See: # https://puck.nether.net/pipermail/juniper-nsp/2017-March/034067.html # and the resulting PR 1265504 (reported from this codebase!) # # As of May 2020, there are still issues with parsing, needing # additional code to parse (address type, address) tuples. snimpy#90. # # This effectively means only IPv4 matches, which is probably okay for # this use case (and probably this decade). load("BGP4-MIB") for router, community in settings.SNMP_ROUTERS.items(): m = M(host=router, community=community, version=2) netixlans = [] notmatched = 0 try: peers = m.bgpPeerRemoteAs for ip, asn in peers.iteritems(): try: netixlan = NetworkIXLan.objects.get(ipaddr4=ip, asn=asn) netixlans.append(netixlan) except NetworkIXLan.DoesNotExist: notmatched += 1 except SNMPException as e: raise CommandError(e) with transaction.atomic(): # flush all peerings for this router Peering.objects.filter(router=router).delete() # ...and recreate them for netixlan in netixlans: p = Peering(netixlan=netixlan, router=router) p.save() print("{}: matched {}, not matched {}".format( router, len(netixlans), notmatched))
def set_cpuStat(self): """ Return cpu infos """ m = M(host=self.snmpTarget, community=self.snmpCommunity, none=True) logging.debug("loading cpu infos [4/x]...") for i in m.cpmCPUTotal5sec: self._cpu_5_sec.append(int(m.cpmCPUTotal5sec[i])) for i in m.cpmCPUTotal1min: self._cpu_1_min.append(int(m.cpmCPUTotal1min[i])) for i in m.cpmCPUTotal5min: self._cpu_5_min.append(int(m.cpmCPUTotal5min[i]))
def has_snmp(self, lock=None): load("SNMPv2-MIB") self.snmp = False try: if lock is not None: lock.acquire() m = M(host=self.host, community=self.snmp_group, version=2, timeout=2) if m.sysName is not None: self.snmp = True if lock is not None: lock.release() except Exception as e: self.has_error("(snmp) " + e.message) self.snmp = False
def handle(self, *args, **options): # only BGP4-MIB for now, there were snimpy troubles with Juniper's BGP # v2 MIB: # http://puck.nether.net/pipermail/juniper-nsp/2017-March/034067.html # # This effectively means only IPv4 matches, which is probably okay for # this use case (and probably this decade). load("BGP4-MIB") for router, community in iteritems(settings.SNMP_ROUTERS): m = M(host=router, community=community, version=2) netixlans = [] notmatched = 0 try: peers = m.bgpPeerRemoteAs for ip, asn in iteritems(peers): try: netixlan = NetworkIXLan.objects.get(ipaddr4=ip, asn=asn) netixlans.append(netixlan) except NetworkIXLan.DoesNotExist: notmatched += 1 except SNMPException as e: raise CommandError(e) with transaction.atomic(): # flush all peerings for this router Peering.objects.filter(router=router).delete() # ...and recreate them for netixlan in netixlans: p = Peering(netixlan=netixlan, router=router) p.save() print("{}: matched {}, not matched {}".format( router, len(netixlans), notmatched))
def __init__(self, target, community): self.snmpTarget = target self.snmpCommunity = community m = M(host=self.snmpTarget, community=self.snmpCommunity, version=2, none=True) self._cpu_5_sec = list() self._cpu_1_min = list() self._cpu_5_min = list() self._mem_Free = list() self._mem_Used = list() self._mem_Alloc = list() logging.debug("loading hostname infos [1/x]...") self.sysName = str(m.sysName) logging.debug("loading sysDescr infos [2/x]...") self.sysDescr = str(m.sysDescr)
print "%s is down" % ip return sw mp = dict( ) # key/value = ip of switch / tuple(switch port/macs on that port) cantquery = [] # list of switches that did not respond to snmp switches = find_switches() # DEBUG # uncomment line below to override switches to speed up testing # switches = {'10.11.12.161':'', '10.11.12.153':''} # query all the switches to retrieve mac addresses list for ip in switches.keys(): print "Connecting to %s..." % ip try: c = M(host=ip, community="public", version=2, timeout=2, retries=1) # get the mac of the switch I'm connected to switches[ip] = str(c.dot1dBaseBridgeAddress) mp[ip] = dict() # return a list of tuples mac / port (not sorted!) for mpm, mpp in c.dot1dTpFdbPort.items(): mac = str(mpm) port = int(mpp) if port not in mp[ip].keys( ): # initiatilize the array for that port mp[ip][port] = [] mp[ip][port].append(mac) except: cantquery.append(ip) pass print "All these switches could not be queried (unreachable or unsupported MIBs): %s" % (
def main(): mib.path(mib.path() + ":/usr/share/mibs/cisco") load("SNMPv2-MIB") load("IF-MIB") load("IP-MIB") load("RFC1213-MIB") load("CISCO-QUEUE-MIB") #Requires MIB RFC-1212 (add to /usr/share/mibs/ietf/) parser = argparse.ArgumentParser() parser.add_argument('-r', '--router', nargs='?', required=True, help='address of router to monitor') parser.add_argument('-s', '--sinterval', type=int, help='sampling interval (seconds)', default=5) args = parser.parse_args() print("time: ", args.sinterval) print("argumentos", args) #Creates SNMP manager for router with address args.router m = M(args.router, 'private', 3, secname='uDDR', authprotocol="MD5", authpassword="******", privprotocol="AES", privpassword="******") print(m.sysDescr) #Gets sysDescr from SNMPv2-MIB print("===") print(m.ifDescr.items() ) #Lists (order, name) interfaces in ifDescr from IF-MIB for i, name in m.ifDescr.items(): print("Interface order %d: %s" % (i, name)) print("===") print( m.ipAddressIfIndex.items() ) #Lists ((adr.type,adr),order) interfaces in ipAddressIfIndex from IP-MIB ifWithAddr = {} #Stores (order, first adr.) of all interfaces PktsOut = {} tempo = args.sinterval print tempo #exercicio 4 while True: time.sleep(args.sinterval) for addr, i in m.ipAddressIfIndex.items( ): # percorre todas as interfaces if not i in ifWithAddr: ifWithAddr.update({i: IPfromOctetString(addr[0], addr[1])}) PktsOut.update({i: m.ifHCOutUcastPkts}) PktsOut.update({i: m.ifHCInUcastPkts}) PktsOut.update({i: m.ifHCOutOctets}) PktsOut.update({i: m.ifHCInOctets}) PktsOut.update({i: m.cQStatsDepth}) #print('%s, Interface order: %d, %s'%(IPfromOctetString(addr[0],addr[1]),i,m.ifDescr[i])) print("") print("---------Initial values---------") print('%s, Interface order: %d, %s' % (IPfromOctetString(addr[0], addr[1]), i, m.ifDescr[i])) print("%s, Packets Out: %s" % (IPfromOctetString(addr[0], addr[1]), m.ifHCOutUcastPkts[i])) print("%s, Packets In: %s" % (IPfromOctetString(addr[0], addr[1]), m.ifHCInUcastPkts[i])) print("%s, Octets Out: %s" % (IPfromOctetString(addr[0], addr[1]), m.ifHCOutOctets[i])) print("%s, Octets In: %s" % (IPfromOctetString(addr[0], addr[1]), m.ifHCInOctets[i])) print("%s, Depth: %s" % (IPfromOctetString(addr[0], addr[1]), m.cQStatsDepth[i, 2])) print("") print(ifWithAddr) print(PktsOut) print("===")
try: # Loading mibs we will need load("DOCS-CABLE-DEVICE-MIB") load("SNMPv2-MIB") load("IF-MIB") load("SNMPv2-SMI") load("DISMAN-EVENT-MIB") load("DOCS-IF-MIB") load("RFC1213-MIB") load("BRIDGE-MIB") load("DOCS-IF31-MIB") load("DOCS-PNM-MIB") load("DOCS-IF-EXT-MIB") modem = str(modem_host) host = M(host=modem, community="public", version=2, timeout=1, retries=2) logs = host.docsDevEvFirstTime cablemac = host.ifPhysAddress[2] mac = EUI(cablemac) mac.dialect = mac_cisco ifIndex = host.ifIndex pilots = host.docsIf31CmDsOfdmChannelPowerCenterFrequency downstream = [] upstream = [] ofdmid = [] ofdmsnr = host.docsPnmCmDsOfdmRxMerMean docsisver = host.docsIfDocsisBaseCapability eth = [] o = 0 for i in ifIndex: ifType = host.ifType[i]
def main(): mib.path(mib.path() + ":/usr/share/mibs/cisco") load("SNMPv2-MIB") load("IF-MIB") load("IP-MIB") load("RFC1213-MIB") load("CISCO-QUEUE-MIB") #Requires MIB RFC-1212 (add to /usr/share/mibs/ietf/) parser = argparse.ArgumentParser() parser.add_argument('-r', '--router', nargs='?', required=True, help='address of router to monitor') parser.add_argument('-s', '--sinterval', type=int, help='sampling interval (seconds)', default=5) args = parser.parse_args() myInterval = args.sinterval print(args) #Creates SNMP manager for router with address args.router m = M(args.router, 'private', 3, secname='uDDR', authprotocol="MD5", authpassword="******", privprotocol="AES", privpassword="******") print(m.sysDescr) #Gets sysDescr from SNMPv2-MIB print("===") print(m.ifDescr.items() ) #Lists (order, name) interfaces in ifDescr from IF-MIB for i, name in m.ifDescr.items(): print("Interface order %d: %s" % (i, name)) print("===") print( m.ipAddressIfIndex.items() ) #Lists ((adr.type,adr),order) interfaces in ipAddressIfIndex from IP-MIB ifWithAddr = {} #Stores (order, first adr.) of all interfaces for addr, i in m.ipAddressIfIndex.items(): if not i in ifWithAddr: ifWithAddr.update({i: IPfromOctetString(addr[0], addr[1])}) print('%s, Interface order: %d, %s' % (IPfromOctetString(addr[0], addr[1]), i, m.ifDescr[i])) print(ifWithAddr) print("===========================================================") f = open("InOutPkts.txt", 'w') fByte = open("InOutBytes.txt", 'w') last_outpackets = [None] * 10 last_inPkts = [None] * 10 last_outByte = [0] * 10 last_inByte = [0] * 10 for i, name in m.ifHCOutUcastPkts.items(): last_outpackets[i] = name for i, name in m.ifHCInUcastPkts.items(): last_inPkts[i] = name for i, name in m.ifHCOutOctets.items(): last_outByte[i] = name for i, name in m.ifHCInOctets.items(): last_inByte[i] = name listInterfaces = [] listValues = [] try: while (True): listInterfaces = [] listValues = [] printFlag = False interval = time.time() if ((interval - lastTime) >= myInterval): global lastTime lastTime = time.time() printFlag = True if (printFlag == True): print(" ==Out Packets==") f.write("Router : %s ==Out Packets==\n" % args.router) for i, name in m.ifHCOutUcastPkts.items(): print( "Interface %d: Packets send in the last interval: %s" % (i, (name - last_outpackets[i]))) f.write( "Interface %d: Packets send in the last interval: %s\n" % (i, (name - last_outpackets[i]))) listInterfaces = listInterfaces + [int(i)] listValues = listValues + [int(name - last_outpackets[i])] last_outpackets[i] = name plt.plot(listInterfaces, listValues) plt.title("Out Packets") plt.ylabel("Out Packets") plt.xlabel("Interfaces") plt.show() print(" ==In Packets==") f.write("Router : %s ==In Packets==\n" % args.router) listInterfaces = [] listValues = [] for i, name in m.ifHCInUcastPkts.items(): print( "Interface %d: Packets receive in the last interval: %s" % (i, (name - last_inPkts[i]))) f.write( "Interface %d: Packets receive in the last interval: %s\n" % (i, (name - last_inPkts[i]))) listInterfaces = listInterfaces + [int(i)] listValues = listValues + [int(name - last_inPkts[i])] last_inPkts[i] = name plt.plot(listInterfaces, listValues) plt.title("==In Packets==") plt.ylabel("In Packets") plt.xlabel("Interfaces") plt.show() f.write("===============================================\n") print(" ==Out Bytes==") listInterfaces = [] listValues = [] fByte.write("Router : %s ==Out Bytes==\n" % args.router) for i, name in m.ifHCOutOctets.items(): print("Interface %d: Bytes send in the last interval: %s" % (i, (name - last_outByte[i]))) fByte.write( "Interface %d: Bytes send in the last interval: %s\n" % (i, (name - last_outByte[i]))) listInterfaces = listInterfaces + [int(i)] listValues = listValues + [int(name - last_outByte[i])] last_outByte[i] = name plt.plot(listInterfaces, listValues) plt.title("==Out Bytes==") plt.ylabel("Out Bytes") plt.xlabel("Interfaces") plt.show() print(" ==In Bytes==") listInterfaces = [] listValues = [] fByte.write("Router : %s ==In Bytes==\n" % args.router) for i, name in m.ifHCInOctets.items(): print( "Interface %d: Bytes receive in the last interval: %s" % (i, (name - last_inByte[i]))) fByte.write( "Interface %d: Bytes receive in the last interval: %s\n" % (i, (name - last_inByte[i]))) listInterfaces = listInterfaces + [int(i)] listValues = listValues + [int(name - last_inByte[i])] last_inByte[i] = name plt.plot(listInterfaces, listValues) plt.title("==In Bytes==") plt.ylabel("In Bytes") plt.xlabel("Interfaces") plt.show() fByte.write( "===============================================\n") except KeyboardInterrupt: f.close() exit
def create(self, devicename='localhost', timeout=None, retries=None, cache=None, bulk=20, none=True, rw=False, community_format='{}'): """Create a new SNMP manager. :param devicename: The hostname or IP address of the agent to connect to. Optionally, the port can be specified separated with a double colon. :type host: str :param timeout: Use the specified value in seconds as timeout. :type timeout: int :param retries: How many times the request should be retried? :type retries: int :param cache: Should caching be enabled? This can be either a boolean or an integer to specify the cache timeout in seconds. If `True`, the default timeout is 5 seconds. :type cache: bool or int :param bulk: Max-repetition to use to speed up MIB walking with `GETBULK`. Set to `0` to disable. :type bulk: int :param none: Should `None` be returned when the agent does not know the requested OID? If `True`, `None` will be returned when requesting an inexisting scalar or column. :type none: bool :param rw: if True, use the SNMPv2 write community instead of the read-only community. :type rw : bool :param community_format : string to use to format the community string used mainly for Cisco VLAN-based communities. :type host: str """ self.logger.debug( 'fn=SNMPmgr/create : %s : creating the snimpy manager' % (devicename)) if timeout is None: timeout = self.app.config['SNMP_TIMEOUT'] if retries is None: retries = self.app.config['SNMP_RETRIES'] if cache is None: cache = self.app.config['SNMP_CACHE'] # get credentials and connection info for this device credentials = self.credmgr.get_credentials(devicename) # if SNMP V2, read-only or read-write ? if rw: community = credentials['rw_community'] else: community = credentials['ro_community'] self.logger.debug( 'fn=SNMPmgr/create : %s : parameters : version=%s, timeout=%s, retries=%s, cache=%s, bulk=%s, none=%s, read-write=%s, community_format=%s' % (devicename, credentials['snmp_version'], timeout, retries, cache, bulk, none, rw, community_format)) # the community might be adjusted using the format if it is defined. # mostly used for VLAN-based communities # Used for Cisco gear, where it is called "community string indexing" community = community_format.format(community) # and now try tro create a manager. try: m = M(host=devicename, community=community, version=credentials['snmp_version'], secname=credentials['secname'], authprotocol=credentials['authprotocol'], authpassword=credentials['authpassword'], privprotocol=credentials['privprotocol'], privpassword=credentials['privpassword'], timeout=timeout, retries=retries, cache=cache, bulk=bulk, none=none) except Exception as e: self.logger.warning( 'fn=SNMPmgr/create : %s : cannot create SNMP manager : <%s>' % (devicename, e)) return None, str(e) self.logger.debug('fn=SNMPmgr/create : %s : returning manager' % (devicename)) return m, ''
def main(): mib.path(mib.path() + ":/usr/share/mibs/cisco") load("SNMPv2-MIB") load("IF-MIB") load("IP-MIB") load("RFC1213-MIB") load("CISCO-QUEUE-MIB") # Requires MIB RFC-1212 (add to /usr/share/mibs/ietf/) parser = argparse.ArgumentParser() parser.add_argument('-r', '--router', nargs='?', required=True, help='address of router to monitor') parser.add_argument('-s', '--sinterval', type=int, help='sampling interval (seconds)', default=5) args = parser.parse_args() sys.stdout = Logger("router_" + args.router) print(args) # Creates SNMP manager for router with address args.router m = M(args.router, 'private', 3, secname='uDDR', authprotocol="MD5", authpassword="******", privprotocol="AES", privpassword="******") print(m.sysDescr) # Gets sysDescr from SNMPv2-MIB print("##################") # print(m.ifDescr.items()) #Lists (order, name) interfaces in ifDescr from IF-MIB for i, name in m.ifDescr.items(): print("Interface order %d: %s" % (i, name)) print("##################") ifWithAddr = {} # Stores the interfaces with IP address for addr, i in m.ipAddressIfIndex.items(): if i not in ifWithAddr: ifWithAddr.update({i: {"ip": ip_from_octet_string(addr[0], addr[1]), "name": m.ifDescr[i]}}) print('%s, Interface order: %d, %s' % (ip_from_octet_string(addr[0], addr[1]), i, m.ifDescr[i])) t = 0 ifOutUCastPkts = {} ifInUCastPkts = {} ifOutOctets = {} ifInOctets = {} ifQstats = {} """ ## load from json with open('router_10.0.0.2.json') as data_file: content = json.load(data_file) ifOutUCastPkts = content["ifOutUCastPkts"] ifInUCastPkts = content["ifInUCastPkts"] ifOutOctets = content["ifOutUCastPkts"] ifInOctets = content["ifOutUCastPkts"] ifQstats = content["ifOutUCastPkts"] draw_plt(ifWithAddr, ifOutUCastPkts, ifInUCastPkts, ifOutOctets, ifInOctets, ifQstats) exit() """ try: prevOutUCastPkts = {} prevInUCastPkts = {} prevOutOctets = {} prevInOctets = {} previfQstats = {} for i in ifWithAddr.keys(): prevOutUCastPkts[i] = 0 prevInUCastPkts[i] = 0 prevOutOctets[i] = 0 prevInOctets[i] = 0 previfQstats[i] = 0 count = 0 while True: print("\n=== %d Seconds passed ===" % t) """ # ifHCOutUcastPkts The total number of packets that higher-level protocols requested be transmitted, and which were not addressed to a multicast or broadcast address at this sub-layer, including those that were discarded or not sent. This object is a 64-bit version of ifOutUcastPkts. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of ifCounterDiscontinuityTime." """ print("\n### ifOutUCastPkts") ifOutUCastPkts[t] = {} for i, pkts in m.ifHCOutUcastPkts.items(): if i in ifWithAddr.keys(): if i not in ifOutUCastPkts[t]: if count == 0: ifOutUCastPkts[t].update({i: 0}) else: ifOutUCastPkts[t].update({i: pkts - prevOutUCastPkts[i]}) prevOutUCastPkts[i] = pkts print('%s, Interface Out packets: %d' % (m.ifDescr[i], ifOutUCastPkts[t][i])) """ The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were not addressed to a multicast or broadcast address at this sub-layer. This object is a 64-bit version of ifInUcastPkts. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of ifCounterDiscontinuityTime. """ print("\n### ifInUCastPkts") ifInUCastPkts[t] = {} for i, pkts in m.ifHCInUcastPkts.items(): if i in ifWithAddr.keys(): if i not in ifInUCastPkts[t]: if count == 0: ifInUCastPkts[t].update({i: 0}) else: ifInUCastPkts[t].update({i: pkts - prevInUCastPkts[i]}) prevInUCastPkts[i] = pkts print('%s, Interface In packets: %d' % (m.ifDescr[i], ifInUCastPkts[t][i])) """ The total number of octets transmitted out of the interface, including framing characters. This object is a 64-bit version of ifOutOctets. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of ifCounterDiscontinuityTime. """ print("\n### ifOutOctets") ifOutOctets[t] = {} for i, pkts in m.ifHCOutOctets.items(): if i in ifWithAddr.keys(): if i not in ifOutOctets[t]: if count == 0: ifOutOctets[t].update({i: 0}) else: ifOutOctets[t].update({i: pkts - prevOutOctets[i]}) prevOutOctets[i] = pkts print('%s, Interface Out octets: %d' % (m.ifDescr[i], ifOutOctets[t][i])) """ The total number of octets received on the interface, including framing characters. This object is a 64-bit version of ifInOctets. Discontinuities in the value of this counter can occur at re-initialization of the management system, and at other times as indicated by the value of ifCounterDiscontinuityTime. """ print("\n### ifInOctets") ifInOctets[t] = {} for i, pkts in m.ifHCInOctets.items(): if i in ifWithAddr.keys(): if i not in ifInOctets[t]: if count == 0: ifInOctets[t].update({i: 0}) else: ifInOctets[t].update({i: pkts - prevInOctets[i]}) prevInOctets[i] = pkts print('%s, Interface In octets: %d' % (m.ifDescr[i], ifInOctets[t][i])) """ The number of messages in the sub-queue. """ print("\n### ifQstats") ifQstats[t] = {} for (i, u), pkts in m.cQStatsDepth.items(): if i in ifWithAddr.keys(): if i not in ifQstats[t]: if count == 0: ifQstats[t].update({i: 0}) else: ifQstats[t].update({i: pkts - previfQstats[i]}) previfQstats[i] = pkts print('%s, Interface Queue Size: %d' % (m.ifDescr[i], ifQstats[t][i])) plt.ion() timeList = [] for t, value in ifOutUCastPkts.items(): timeList.append(int(t)) timeList = sorted(timeList, key=int) for i, details in ifWithAddr.items(): fig = plt.figure(i, figsize=(16, 10), dpi=80) fig.canvas.set_window_title(str(details["name"]) + ' ' + str(details["ip"])) fig.subplots_adjust(wspace=0.23) # ifOutUCastPkts xitems = timeList yitems = [] for t in timeList: yitems.append(ifOutUCastPkts[t][i]) plt.subplot(231) plt.plot(xitems, yitems) plt.title("Interface out") plt.xlabel("time (s)") plt.ylabel("Unicast packets") plt.grid(True) # ifInUCastPkts xitems = timeList yitems = [] for t in timeList: yitems.append(ifInUCastPkts[t][i]) plt.subplot(232) plt.plot(xitems, yitems) plt.title("Interface in") plt.ylabel("Unicast packets") plt.xlabel("time (s)") plt.grid(True) # ifOutOctets xitems = timeList yitems = [] for t in timeList: yitems.append(ifOutOctets[t][i]) plt.subplot(233) plt.plot(xitems, yitems) plt.title("Number of bytes transmitted") plt.ylabel("Number of bytes") plt.xlabel("time (s)") plt.grid(True) # ifInOctets xitems = timeList yitems = [] for t in timeList: yitems.append(ifInOctets[t][i]) plt.subplot(234) plt.plot(xitems, yitems) plt.title("Number of bytes received") plt.ylabel("Number of bytes") plt.xlabel("time (s)") plt.grid(True) plt.draw() # ifQstats xitems = timeList yitems = [] for t in timeList: yitems.append(ifQstats[t][i]) plt.subplot(235) plt.plot(xitems, yitems) plt.title("The number of messages in the sub-queue.") plt.ylabel("Number of messages") plt.xlabel("time (s)") plt.grid(True) plt.draw() time.sleep(args.sinterval) t += args.sinterval count += 1 except KeyboardInterrupt: print "Finished after %d seconds..." % t json_save(args, ifWithAddr, ifOutUCastPkts, ifInUCastPkts, ifOutOctets, ifInOctets, ifQstats)
#!/usr/bin/python from snimpy.manager import Manager as M from snimpy.manager import load load("/usr/share/snmp/mibs/IF-MIB.mib") m = M("ipmi-sw01", 'snmp-com-ro', 2) print m.ifTable
config.INFLUX_PORT, config.INFLUX_USER, config.INFLUX_PASSWORD, config.INFLUX_DATABASE, ) try: res = INFLUX.create_database(config.INFLUX_DATABASE) except: pass load("/app/UPSMonitor/RFC1155-SMI.txt") load("/app/UPSMonitor/RFC-1215") load("/app/UPSMonitor/RFC-1212-MIB.txt") load("/app/UPSMonitor/RFC1213-MIB.txt") load("/app/UPSMonitor/stdupsv1.mib") m = M("172.16.14.36", "NARpublic", 1) model = m.upsIdentModel manuf = m.upsIdentManufacturer def job(): points = [] points.append(dict( measurement="ups_battery_voltage", tags=dict( model=model, manufacturer=manuf ), time=datetime.utcnow(), fields=dict( value=m.upsBatteryVoltage
from snimpy.manager import Manager as M from snimpy.manager import load import time import paho.mqtt.client as mqtt while True: load("IF-MIB") m = M(host="192.168.2.1", community="wtpublic", version=1) ifspeed = m.ifSpeed[2] OutOctet1 = m.ifOutOctets[2] InOctet1 = m.ifInOctets[2] time.sleep(1) m = M(host="192.168.2.1", community="wtpublic", version=1) OutOctet2 = m.ifOutOctets[2] InOctet2 = m.ifInOctets[2] upload = float((((float(OutOctet2) - float(OutOctet1)) * 8) * 100) / (float(ifspeed) * 1)) download = float((((float(InOctet2) - float(InOctet1)) * 8) * 100) / (float(ifspeed) * 1)) mqttc = mqtt.Client("python_pub") mqttc.connect("192.168.2.17", 1883) mqttc.publish("bandwidth/up", upload) time.sleep(1) mqttc.publish("bandwidth/down", download) mqttc.loop(2) time.sleep(5)
def cpu(h, thr_cpu=None, thr_uptime=None): ip = "88.184.233.4" cid = "xymon" m = M(ip, cid) if not thr_cpu: thr_cpu = (60, 80) if not thr_uptime: thr_uptime = (600, 5000) thr_cpu_message = { 'red': '&red CPU utilization is very high', 'yellow': '&yellow CPU utilization is high', 'green': '&green CPU utilization is nominal' } thr_uptime_message = { 'red': '&red Device rebooted recently. System uptime', 'yellow': '&yellow Device rebooted recently. System uptime', 'green': '&green System uptime' } cpu_oids = ['cpmCPUTotal5minRev', 'cpmCPUTotal5min'] now = str(dt.now()) graph = [] cpu_color = uptime_color = "red" uptime_message = cpu_message = alert = "" hostname = m.sysName if hasattr(m, 'sysName') else None model = m.entPhysicalDescr[1] if hasattr(m, 'entPhysicalDescr') else None version = m.sysDescr if hasattr(m, 'sysDescr') else None uptime = m.sysUpTime if hasattr(m, 'sysUpTime') else 0 if uptime > thr_uptime[0]: uptime_color = "yellow" if uptime > thr_uptime[1]: uptime_color = "green" if 'green' not in uptime_color: alert += thr_uptime_message[uptime_color] uptime_message = '%s : %s' %\ (thr_uptime_message[uptime_color], str(uptime)) for oid in cpu_oids: if hasattr(m, oid): for value in getattr(m, oid): if value > thr_cpu[0] and value < thr_cpu[1]: cpu_color = 'yellow' elif value < thr_cpu[0]: cpu_color = 'green' cpu_message += "%s : %s%%\n"\ % (thr_cpu_message[cpu_color], str(value)) if 'green' not in cpu_color: alert += thr_cpu_message[cpu_color] graph.append(value) break message = "%s\n\n%s\n\nHostname : %s\nModel: %s\n\n%s\n\n%s\n\nSystem description: %s"\ % (now, alert, hostname, model, uptime_message, cpu_message, version) if '&yellow' in message: color = 'yellow' elif '&red' in message: color = 'red' else: color = 'green' send_to_xy('status %s.cpu %s\n%s' % (h, color, message)) return message
snmphost = os.getenv('snmphost','127.0.0.1') snmpcommunity = os.getenv('snmpcommunity') print (snmpcommunity) mqtthost = os.getenv('mqtthost','127.0.0.1') print (mqtthost) mqttport = os.getenv('mqttport',1883) print (mqttport) print (snmphost) while True: load("IF-MIB") m = M(host=snmphost, community=snmpcommunity,version = 1) ifspeed= m.ifSpeed[2] OutOctet1 = m.ifInOctets[2] InOctet1 = m.ifOutOctets[2] time.sleep(1) m = M(host=snmphost, community=snmpcommunity,version = 1) OutOctet2 = m.ifInOctets[2] InOctet2 = m.ifOutOctets[2] upload= float(float(OutOctet2) - float(OutOctet1))*8 download=float(float(InOctet2) - float(InOctet1))*8 mqttc = mqtt.Client("python_pub") print (upload) print (download) mqttc.connect(mqtthost,mqttport) mqttc.publish("bandwidth/up", upload) mqttc.publish("bandwidth/down",download)