def testSetPath(self): """Test we can set path to some value""" original = mib.path() current = original + ":/some/other/directory" try: mib.path(current) self.assertEqual(mib.path(), current) finally: mib.path(original)
from snimpy.mib import path import socket from datetime import datetime as dt from celery import Celery import sys import pprint celery = Celery('pxynmp', broker='redis://localhost', backend='redis://localhost') host = "oc-argenteuil" path('/var/lib/snmp/mibs/cisco:' + path()) load('CISCO-PROCESS-MIB') load('ENTITY-MIB') load('IF-MIB') load('SNMPv2-MIB') def is_connected(m): try: m.sysUpTime except: return False return True def send_to_xy(msg):
def testGetPath(self): """Test we can get default SMI path""" current = mib.path() self.assertTrue(type(current), unicode) self.assertNotEqual(mib.path(), u"")
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("===")
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) #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 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])}) t = 0 fig = plt.figure(num=None, figsize=(10, 7.5), dpi=80) plt.subplots_adjust(wspace=0.25) plt.subplots_adjust(hspace=0.25) plt.ion() try: inPkts = {} inPktsDiference = {} outPkts = {} outPktsDiference = {} inOcts = {} inOctsDiference = {} outOcts = {} outOctsDiference = {} colors = {} colormap = ['r.-','y.-','g.-','b.-','m.-'] counter = 0 patches=[] for i, name in m.ifDescr.items(): if i in ifWithAddr: inPkts.update({name:[]}) inPktsDiference.update({name:[]}) outPkts.update({name:[]}) outPktsDiference.update({name:[]}) inOcts.update({name:[]}) inOctsDiference.update({name:[]}) outOcts.update({name:[]}) outOctsDiference.update({name:[]}) colors.update({name:colormap[counter]}) counter +=1 if counter >= len(colormap): counter =0 counter = 0 while True: ifOutUCastPkts={} #Stores (order, OutPkts) of all interfaces for i, pkts in m.ifHCOutUcastPkts.items(): if i in ifWithAddr.keys(): if not i in ifOutUCastPkts: ifOutUCastPkts.update({i:pkts}) ifInUCastPkts={} #Stores (order, InPkts) of all interfaces for i, pkts in m.ifHCInUcastPkts.items(): if i in ifWithAddr.keys(): if not i in ifInUCastPkts: ifInUCastPkts.update({i:pkts}) ifOutOctets={} #Stores (order, OutOctets) of all interfaces for i, pkts in m.ifHCOutOctets.items(): if i in ifWithAddr.keys(): if not i in ifOutOctets: ifOutOctets.update({i:pkts}) ifInOctets={} #Stores (order, InOctets) of all interfaces for i, pkts in m.ifHCInOctets.items(): if i in ifWithAddr.keys(): if not i in ifInOctets: ifInOctets.update({i:pkts}) ifQstats={} #Stores (order, queue_size) of all interfaces for (i,u),pkts in m.cQStatsDepth.items(): if i in ifWithAddr.keys(): if not i in ifQstats: ifQstats.update({i:pkts}) x = np.arange(0, t+args.sinterval, 5) order = [] aux = 0 print("=== %d Seconds passed ===" % t) for i, name in m.ifDescr.items(): if i in ifWithAddr: print("%s, %s \t pkts[in/out][%s/%s] \t octets[in/out][%s/%s] \t queue[%s]" % (ifWithAddr[i], name, ifInUCastPkts[i], ifOutUCastPkts[i], ifInOctets[i], ifOutOctets[i], ifQstats[i])) order.append(name) #Plot in Packets plt.subplot(2, 2, 1) plt.title('In Packets') plt.ylabel('Packets') inPkts[name] += [ifInUCastPkts[i]] inPktsDiference[name] += [ifInUCastPkts[i]] if(counter != 0): if counter==1: inPktsDiference[name][1] = inPkts[name][1]-inPkts[name][0] inPktsDiference[name][0] = 0 else: inPktsDiference[name][counter] = inPkts[name][counter]-inPkts[name][counter-1] plt.plot(x, inPktsDiference[name], colors[name]) else: plt.plot(x, 0, colors[name]) #Plot out Packets plt.subplot(2, 2, 2) plt.title('Out Packets') outPkts[name] += [ifOutUCastPkts[i]] outPktsDiference[name] += [ifOutUCastPkts[i]] if(counter != 0): if counter==1: outPktsDiference[name][1] = outPkts[name][1]-outPkts[name][0] outPktsDiference[name][0] = 0 else: outPktsDiference[name][counter] = outPkts[name][counter]-outPkts[name][counter-1] plt.plot(x, outPktsDiference[name], colors[name]) else: plt.plot(x, 0, colors[name]) #Plot in Octets plt.subplot(2, 2, 3) plt.title('In Octets') plt.xlabel('Time (s)') plt.ylabel('Octets') inOcts[name] += [ifInOctets[i]] inOctsDiference[name] += [ifInOctets[i]] if(counter != 0): if counter==1: inOctsDiference[name][1] = inOcts[name][1]-inOcts[name][0] inOctsDiference[name][0] = 0 else: inOctsDiference[name][counter] = inOcts[name][counter]-inOcts[name][counter-1] plt.plot(x, inOctsDiference[name], colors[name]) else: plt.plot(x, 0, colors[name]) #Plot out Octets plt.subplot(2, 2, 0) plt.title('Out Octets') plt.xlabel('Time (s)') outOcts[name] += [ifOutOctets[i]] outOctsDiference[name] += [ifOutOctets[i]] if(counter != 0): if counter==1: outOctsDiference[name][1] = outOcts[name][1]-outOcts[name][0] outOctsDiference[name][0] = 0 else: outOctsDiference[name][counter] = outOcts[name][counter]-outOcts[name][counter-1] plt.plot(x, outOctsDiference[name], colors[name]) else: plt.plot(x, 0, colors[name]) aux+=1 print("========================") counter+=1 plt.subplot(2, 2, 1) plt.legend(order, ncol=4, loc='upper center', bbox_to_anchor=[1.1, 1.3], columnspacing=1.0, labelspacing=0.0,handletextpad=0.0, handlelength=1.5, fancybox=True, shadow=True) plt.draw() time.sleep(args.sinterval) t += args.sinterval except KeyboardInterrupt: print "Finished after %d seconds..." % t fig.savefig('output.jpg') sys.stdout.close()
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)
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