Esempio n. 1
0
def main():
    #List of oid's to collect each polling
    OIDS = {
        'ifName_fa4': '.1.3.6.1.2.1.31.1.1.1.1.5',
        'ifDescr_fa4': '1.3.6.1.2.1.2.2.1.2.5',
        'ifInOctets_fa4': '1.3.6.1.2.1.2.2.1.10.5',
        'ifInUcastPkts_fa4': '1.3.6.1.2.1.2.2.1.11.5',
        'ifOutOctets_fa4': '1.3.6.1.2.1.2.2.1.16.5',
        'ifOutUcastPkts_fa4': '1.3.6.1.2.1.2.2.1.17.5',
    }
    device = ('184.105.247.70',161)
    snmp_user = ('pysnmp', 'galileo1', 'galileo1')
    device_name = snmp_helper.snmp_extract(snmp_helper.snmp_get_oid_v3(device, snmp_user, oid='.1.3.6.1.2.1.1.5.0'))
    filename = device_name + ".fa4.pkl"
    #Read in any existing objects from the pickle jar
    try:
        f = open(filename, "rb")
        samples = pickle.load(f)
        f.close()
    except:
        samples = []
        print "Couldn't open pickle jar" 
    #Collect input and output octets and unicast packets on interface FA4 on pynet-rtr1 every
    collection = { 'timestamp': time.time() }
    for oid in OIDS:
        collection[oid] = snmp_helper.snmp_extract(snmp_helper.snmp_get_oid_v3(device, snmp_user, oid=OIDS[oid]))
    ## I'm having trouble with data structures.  It seems to me that maybe I should create a dictionary of dictionaries here?  ie, have { timestamp: sample }, where timestamp is the actual timestamp, and sample is a dictionary containing all of the OID key/value pairs?  Then I'd be able to sort the top level dictionary and pull out values of the inner one?  not sure.  I get the distinctive feeling I'm making it more complex than it needs to be, and have got it to a place whre 'it works', so I'm leaving it for now.  Suggestions are welcomed.
    samples.append(collection)
    #Write it back out to file
    with open(filename, 'wb+') as f:
        pickle.dump(samples, f) 
Esempio n. 2
0
def main():
    a_user = '******'
    auth_key = 'galileo1'
    encrypt_key = 'galileo1'
    rtr_ip = '50.76.53.27'
    snmp_user = (a_user, auth_key, encrypt_key)
    f = open(device_file, "rb")

    #prev_rtr1_info = pickle.load(f)
    #prev_rtr2_info = pickle.load(f)
    #f.close()

    pynet_rtr1 = (rtr_ip, 7961)
    pynet_rtr2 = (rtr_ip, 8061)


    if hostname == "pynet-rtr1":
        router = pynet_rtr1
    elif hostname == "pynet-rtr2":
        router = pynet_rtr2

    rtr_name = snmp_get_oid_v3(router,snmp_user,oid=router_name)
    rtr_description = snmp_get_oid_v3(router,snmp_user,oid=router_description)
    rtr_uptime = snmp_get_oid_v3(router,snmp_user,oid=router_uptime)
    last_changed = snmp_get_oid_v3(router,snmp_user,oid=config_last_changed)

    name_output = snmp_extract(rtr_name)
    desc_output = snmp_extract(rtr_description)
    uptime_output = snmp_extract(rtr_uptime)
    changed_output = snmp_extract(last_changed)

    device_info = (name_output,desc_output,uptime_output,changed_output)

    compare_device_info(hostname, device_info)
Esempio n. 3
0
def main():

    # SNMPv3 Connection Parameters
    a_user = '******'
    auth_key = '*************'
    encrypt_key = '*************'
    snmp_user = (a_user, auth_key, encrypt_key)

    if (pickle.load(open("rout2.p", "rb"))):
        LAST_RUN_CHANGE = pickle.load(open("rout2.p", "rb"))

    else:
        LAST_RUN_CHANGE = int(
            snmp_extract(
                snmp_get_oid_v3(router2, snmp_user,
                                ccmHistoryRunningLastChanged)))
        pickle.dump(LAST_RUN_CHANGE, open("rout2.p", "wb"))
        print "last run saved"
        quit()

    NEW_RUN_CHANGE = snmp_extract(
        snmp_get_oid_v3(router2, snmp_user, ccmHistoryRunningLastChanged))

    if NEW_RUN_CHANGE > LAST_RUN_CHANGE:
        print "Running config changed"
        subject = 'Test message'
        message = '''

		The running config has changed.
		Regards,

		Sean
		'''

        send_mail(subject, message)
Esempio n. 4
0
	def get_sysinfo(self):
		# Uptime when running config last changed
		ccmHistoryRunningLastChanged = '1.3.6.1.4.1.9.9.43.1.1.1.0'   

		# Uptime when running config last saved (note any 'write' constitutes a save)    
		ccmHistoryRunningLastSaved = '1.3.6.1.4.1.9.9.43.1.1.2.0'   

		# Uptime when startup config last saved   
		ccmHistoryStartupLastChanged = '1.3.6.1.4.1.9.9.43.1.1.3.0'

		#system uptime
		sysUptime = '1.3.6.1.2.1.1.3.0'

		oidRunningLastChanged = snmp_helper.snmp_get_oid_v3(self.a_device, self.snmp_user, ccmHistoryRunningLastChanged, display_errors=True)
		self.RunningLastChanged = snmp_helper.snmp_extract(oidRunningLastChanged)
		oidRunningLastSaved = snmp_helper.snmp_get_oid_v3(self.a_device, self.snmp_user, ccmHistoryRunningLastSaved, display_errors=True)
		self.RunningLastSaved = snmp_helper.snmp_extract(oidRunningLastSaved)
		oidStartupLastChanged = snmp_helper.snmp_get_oid_v3(self.a_device, self.snmp_user, ccmHistoryStartupLastChanged, display_errors=True)
		self.StartupLastChanged = snmp_helper.snmp_extract(oidStartupLastChanged)
		sysuptime_oid = snmp_helper.snmp_get_oid_v3(self.a_device, self.snmp_user, sysUptime, display_errors=True)
		self.sysuptime = snmp_helper.snmp_extract(sysuptime_oid)
		sysname_oid = snmp_helper.snmp_get_oid_v3(self.a_device, self.snmp_user, '.1.3.6.1.2.1.1.5.0', display_errors=True)
		self.sysName = snmp_helper.snmp_extract(sysname_oid)
		print "\n" + self.sysName
		print "uptime %s" % self.sysuptime
		self.RunningLastChangedDelta = int(self.sysuptime) - int(self.RunningLastChanged)
		self.RunningLastSavedDelta = int(self.sysuptime) - int(self.RunningLastSaved)
		self.StartupLastChangedDelta = int(self.sysuptime) - int(self.StartupLastChanged)
		print "running changed %s delta %i minutes" % (self.RunningLastChanged, self.RunningLastChangedDelta/6000)
		print "running saved %s delta %i minutes" % (self.RunningLastSaved, self.RunningLastSavedDelta/6000)
		print "startup changed %s delta %i minutes" % (self.StartupLastChanged, self.StartupLastChangedDelta/6000)
Esempio n. 5
0
def main():
    a_user = '******'
    auth_key = 'galileo1'
    encrypt_key = 'galileo1'
    rtr_ip = '50.76.53.27'
    snmp_user = (a_user, auth_key, encrypt_key)

    #prev_rtr1_info = pickle.load(f)
    #print(prev_rtr1_info)
    #prev_rtr2_info = pickle.load(f)
    #print(prev_rtr2_info)

    f = open(device_file, "wb")

    pynet_rtr1 = (rtr_ip, 7961)
    pynet_rtr2 = (rtr_ip, 8061)

    for router in (pynet_rtr1, pynet_rtr2):
        rtr_name = snmp_get_oid_v3(router,snmp_user,oid=router_name)
        rtr_description = snmp_get_oid_v3(router,snmp_user,oid=router_description)
        rtr_uptime = snmp_get_oid_v3(router,snmp_user,oid=router_uptime)
        last_changed = snmp_get_oid_v3(router,snmp_user,oid=config_last_changed)

        name_output = snmp_extract(rtr_name)
        desc_output = snmp_extract(rtr_description)
        uptime_output = snmp_extract(rtr_uptime)
        changed_output = snmp_extract(last_changed)
    
        device_info = (name_output,desc_output,uptime_output,changed_output)

        pickle.dump(device_info, f)
    f.close()
def was_config_changed( router, snmp_user ):

    # System up time
    sysUptimeOID = '1.3.6.1.2.1.1.3.0'
    # Uptime when running config last changed
    ccmHistoryRunningLastChanged = '1.3.6.1.4.1.9.9.43.1.1.1.0'   

    # Uptime when running config last saved (note any 'write' constitutes a save)    
    ccmHistoryRunningLastSaved = '1.3.6.1.4.1.9.9.43.1.1.2.0'   

    # Uptime when startup config last saved   
    ccmHistoryStartupLastChanged = '1.3.6.1.4.1.9.9.43.1.1.3.0'

    snmp_data = snmp_helper.snmp_get_oid_v3(router, snmp_user, oid=sysUptimeOID)
    router_uptime = int(snmp_helper.snmp_extract(snmp_data))
#    print 'uptime:  ' + str( router_uptime ) + ': ' + covert_seconds_to_human_time( router_uptime )

    snmp_data = snmp_helper.snmp_get_oid_v3(router, snmp_user, oid=ccmHistoryRunningLastChanged)
    running_last_change_time = int(snmp_helper.snmp_extract(snmp_data))
#    print 'running last change: ' + str( running_last_change_time ) + ' ' + str( router_uptime - running_last_change_time )

    snmp_data = snmp_helper.snmp_get_oid_v3(router, snmp_user, oid=ccmHistoryRunningLastSaved)
    running_last_save_time = int(snmp_helper.snmp_extract(snmp_data))
#    print 'running last save:   ' + str( running_last_save_time ) + ' ' + str( router_uptime - running_last_save_time )

    snmp_data = snmp_helper.snmp_get_oid_v3(router, snmp_user, oid=ccmHistoryStartupLastChanged)
    startup_last_change_time = int(snmp_helper.snmp_extract(snmp_data))
#    print 'startup last change: ' + str( startup_last_change_time ) + ' ' + str( router_uptime - startup_last_change_time )

    if (running_last_change_time > 600 and (running_last_change_time > startup_last_change_time)):
        output = covert_seconds_to_human_time(router_uptime - running_last_change_time) + 'since last change of running config\n'
        output += covert_seconds_to_human_time(router_uptime - startup_last_change_time) + 'since last save of running config\n'
        return output

    return ''
Esempio n. 7
0
def gen_conf_record(dev_list):
    '''
    Takes a list of Cisco device IP addresses, and queries each device's sysuptime, runn_conf_last_change,
    runn_conf_last_saved, and sysname via SNMPv3.
    
    Returns a dict of list of sys_name, runn_last_changed, runn_last_saved, current_time_in_secs as a a value 
    of each device.
    '''
    conf_record = {}
    for device in dev_list:
        snmp_data = snmp_helper.snmp_get_oid_v3((device, 161),
                                                snmp_user,
                                                oid=SYS_UP_TIME)
        sys_up = snmp_helper.snmp_extract(snmp_data)
        snmp_data = snmp_helper.snmp_get_oid_v3((device, 161),
                                                snmp_user,
                                                oid=RUNN_LAST_CHANGED)
        runn_last_changed = snmp_helper.snmp_extract(snmp_data)
        snmp_data = snmp_helper.snmp_get_oid_v3((device, 161),
                                                snmp_user,
                                                oid=RUNN_LAST_SAVED)
        runn_last_saved = snmp_helper.snmp_extract(snmp_data)
        snmp_data = snmp_helper.snmp_get_oid_v3((device, 161),
                                                snmp_user,
                                                oid=SYS_NAME)
        sys_name = snmp_helper.snmp_extract(snmp_data)
        conf_record[device] = [
            sys_name, sys_up, runn_last_changed, runn_last_saved,
            time.time()
        ]
    return conf_record
Esempio n. 8
0
def main():
    a_user = '******'
    auth_key = 'galileo1'
    encrypt_key = 'galileo1'
    rtr_ip = '50.76.53.27'
    snmp_user = (a_user, auth_key, encrypt_key)
    f = open(device_file, "rb")

    prev_rtr1_info = pickle.load(f)
    prev_rtr2_info = pickle.load(f)
    f.close()

    pynet_rtr1 = (rtr_ip, 7961)
    pynet_rtr2 = (rtr_ip, 8061)

    hostname = raw_input("Please enter the hostname: ")

    if hostname == "pynet-rtr1":
        router = pynet_rtr1
    elif hostname == "pynet-rtr2":
        router = pynet_rtr2

    rtr_name = snmp_get_oid_v3(router,snmp_user,oid=router_name)
    rtr_description = snmp_get_oid_v3(router,snmp_user,oid=router_description)
    rtr_uptime = snmp_get_oid_v3(router,snmp_user,oid=router_uptime)
    last_changed = snmp_get_oid_v3(router,snmp_user,oid=config_last_changed)

    name_output = snmp_extract(rtr_name)
    desc_output = snmp_extract(rtr_description)
    uptime_output = snmp_extract(rtr_uptime)
    changed_output = snmp_extract(last_changed)
    
    device_info = (name_output,desc_output,uptime_output,changed_output)
    
    if hostname == "pynet-rtr1":
        print(device_info[3], prev_rtr1_info[3])
        if device_info[3] > prev_rtr1_info[3]:
            f = open(device_file, "wb")
            pickle.dump(device_info,f)
            pickle.dump(prev_rtr2_info,f)
            f.close()
        else:
            print("No changes have been made to this device.")

    elif hostname == "pynet-rtr2":
        if device_info[3] > prev_rtr2_info[3]:
            print("Device configuration has been changed.")
            f = open(device_file, "wb")
            pickle.dump(prev_rtr1_info,f)
            pickle.dump(device_info,f)
            f.close()
        else:
            print("No changes have been made to this device.")

    f = open("device_info.pkl", "rb")

    prev_rtr1_info = pickle.load(f)
    prev_rtr2_info = pickle.load(f)
    f.close()
Esempio n. 9
0
def if_octects(interval=300, duration=3600):
    '''
    (Optionally) Takes the interval (in secs) and duration (in secs), and queries the device port in and out octects via 
    SNMPv3 every interval for the duration time.
    
    Returns 3 lists in order: if_in_octects, if_out_octects, graph_x_labels (These value lists will be used to graph 
    if_in_octects and if_out_octects via pygal)
    '''
    if_in_octects = []
    if_out_octects = []
    graph_x_labels = []

    snmp_data = snmp_helper.snmp_get_oid_v3((rtr1, 161),
                                            snmp_user,
                                            oid=ifInOctets_fa4)
    base_in_octects = snmp_helper.snmp_extract(snmp_data)
    #print base_in_octects
    snmp_data = snmp_helper.snmp_get_oid_v3((rtr1, 161),
                                            snmp_user,
                                            oid=ifOutOctets_fa4)
    base_out_octects = snmp_helper.snmp_extract(snmp_data)
    #print base_out_octects

    for i in range(duration / interval):
        time.sleep(interval)
        snmp_data = snmp_helper.snmp_get_oid_v3((rtr1, 161),
                                                snmp_user,
                                                oid=ifInOctets_fa4)
        in_octects = snmp_helper.snmp_extract(snmp_data)
        #print in_octects
        snmp_data = snmp_helper.snmp_get_oid_v3((rtr1, 161),
                                                snmp_user,
                                                oid=ifOutOctets_fa4)
        out_octects = snmp_helper.snmp_extract(snmp_data)
        #print out_octects
        if_in_octects.append(int(in_octects) - int(base_in_octects))
        #print if_in_octects
        if_out_octects.append(int(out_octects) - int(base_out_octects))
        #print if_out_octects
        base_in_octects = in_octects
        base_out_octects = out_octects

    if interval >= 60:
        for i in range(duration / interval):
            graph_val = str(((i + 1) * interval / 60.0))
            graph_x_labels.append(graph_val + "m")
    else:
        for i in range(duration / interval):
            graph_val = str(((i + 1) * interval))
            graph_x_labels.append(graph_val + "s")

    #print if_in_octects
    #print if_out_octects
    #print graph_x_labels
    return (if_in_octects, if_out_octects, graph_x_labels)
Esempio n. 10
0
def get_oid_val(oid, rtr=pynet_rtr1):
    """Takes a router (IP, Port) and an OID and returns corresponding OID value"""
    a_user = '******'
    auth_key = 'galileo1'
    encrypt_key = 'galileo1'
    snmp_user = (a_user, auth_key, encrypt_key)
    if oid == '1.3.6.1.2.1.2.2.1.2.5':
        value = snmp_extract(snmp_get_oid_v3(rtr, snmp_user, oid=oid))
    else:
        value = int(snmp_extract(snmp_get_oid_v3(rtr, snmp_user, oid=oid)))
    return value
Esempio n. 11
0
def get_interface_stats(snmp_device, snmp_user, stat_type, row_number):
    '''
    stat_type can be 'in_octets, out_octets, in_ucast_pkts, out_ucast_pkts

    returns the counter value as an integer
    '''

    oid_dict = {
        'in_octets':    '1.3.6.1.2.1.2.2.1.10',
        'out_octets':   '1.3.6.1.2.1.2.2.1.16',
        'in_ucast_pkts':    '1.3.6.1.2.1.2.2.1.11',
        'out_ucast_pkts':    '1.3.6.1.2.1.2.2.1.17',
    }

    if not stat_type in oid_dict.keys():
        raise ValueError("Invalid value for stat_type: {}" % stat_type)

    # Make sure row_number can be converted to an int
    row_number = int(row_number)

    # Append row number to OID
    oid = oid_dict[stat_type]
    oid = oid + '.' + str(row_number)

    snmp_data = snmp_get_oid_v3(snmp_device, snmp_user, oid)
    return int(snmp_extract(snmp_data))
Esempio n. 12
0
def snmp_get(whichrouter, which_oid):
    """
    Get snmp result based on which router and OID
    """
    snmp_data = snmp_helper.snmp_get_oid_v3(whichrouter, snmp_user, oid=which_oid)
    snmp_result = snmp_helper.snmp_extract(snmp_data)
    return snmp_result
Esempio n. 13
0
def main():
    run_last_changed = '1.3.6.1.4.1.9.9.43.1.1.1.0'
    uptime = get_snmp_uptime(a_device, snmp_user)
    device_name = get_snmp_system_name(a_device, snmp_user)
    last_changed = int(
        snmp_extract(snmp_get_oid_v3(a_device, snmp_user,
                                     oid=run_last_changed)))
    get_snmp_system_name(a_device, snmp_user)
    get_snmp_uptime(a_device, snmp_user)
    create_new_device(device_name, uptime, last_changed)

    current_time = datetime.now()
    recipient = '*****@*****.**'
    subject = 'Device {} was modified'.format(device_name)
    message = '''
    
    The running configuration of {} was modified.
    This change was detected at: {}
    
    
    Regards,
    
    Bouchaib
    
    '''.format(device_name, current_time)

    sender = '*****@*****.**'
    email_helper.send_mail(recipient, subject, message, sender)
Esempio n. 14
0
def get_snmp_data (router_data, oid):

    if router_data ['snmp_v'] < 3:

        a_device = ( 
                router_data['IP'], 
                router_data['SNMP Community'], 
                router_data['SNMP Port'], 
        )

        snmp_data = snmp_get_oid ( a_device, oid)

        if snmp_data:
            return snmp_extract (snmp_data)

    if router_data ['snmp_v'] == 3:
        a_device = ( 
                router_data['IP'], 
                router_data['SNMP Port'], 
        )
        snmp_user = router_data ['snmp_user']

        snmp_data = snmp_get_oid_v3 ( a_device, snmp_user, oid)

        if snmp_data:
            return snmp_extract (snmp_data)
    
            
    return None
Esempio n. 15
0
def get_snmp_conf_time(snmp_conf, snmp_oids):
    snmp_tmp = {}
    for oid_name, oid in snmp_oids:
        snmp_device = (snmp_conf['ip_addr'], int(snmp_conf['snmp_port']))
        snmp_user = (snmp_conf['snmp_user'], snmp_conf['snmp_auth_key'], snmp_conf['snmp_encrypt_key'])
        snmp_tmp[oid_name] = int(snmp_extract(snmp_get_oid_v3(snmp_device, snmp_user, oid))) / 100
    return snmp_tmp # Return dictionary with uptime and run|start time
Esempio n. 16
0
def get_interface_stats(snmp_device, snmp_user, stat_type, row_number):
    '''
    stat_type can be 'in_octets, out_octets, in_ucast_pkts, out_ucast_pkts

    returns the counter value as an integer
    '''

    oid_dict = {
        'in_octets': '1.3.6.1.2.1.2.2.1.10',
        'out_octets': '1.3.6.1.2.1.2.2.1.16',
        'in_ucast_pkts': '1.3.6.1.2.1.2.2.1.11',
        'out_ucast_pkts': '1.3.6.1.2.1.2.2.1.17',
    }

    if not stat_type in oid_dict.keys():
        raise ValueError("Invalid value for stat_type: {}" % stat_type)

    # Make sure row_number can be converted to an int
    row_number = int(row_number)

    # Append row number to OID
    oid = oid_dict[stat_type]
    oid = oid + '.' + str(row_number)

    snmp_data = snmp_get_oid_v3(snmp_device, snmp_user, oid)
    return int(snmp_extract(snmp_data))
Esempio n. 17
0
def main():
    a_user = '******'
    auth_key = 'galileo1'
    encrypt_key = 'galileo1'

    pynet_rtr1 = ('184.105.247.70', SNMP_PORT)
    pynet_rtr2 = ('184.105.247.71', SNMP_PORT)

    snmp_user = (a_user, auth_key, encrypt_key)

    for a_device in (pynet_rtr1, pynet_rtr2):
        snmp_results = []
        for oid in (SYS_NAME, SYS_UPTIME, RUN_LAST_CHANGED):
            try:
                value = snmp_extract(
                    snmp_get_oid_v3(a_device, snmp_user, oid=oid))
                snmp_results.append(int(value))
            except ValueError:
                snmp_results.append(value)

        device_name, uptime, last_changed = snmp_results

        if DEBUG:
            print "\nConnected to device = {0}".format(device_name)
            print "Last changed timestamp = {0}".format(last_changed)
            print "Uptime = {0}".format(uptime)
Esempio n. 18
0
def main():
    '''
    main routine
    '''


    pickle_file = 'machine_file.pkl'

    ip_address = raw_input("Enter IP address: ")
    machines = ((ip_address, '7961'), (ip_address, '8061'))
    username = raw_input("Enter SNMPv3 Username: "******"Enter Authentication key: ")
    encryption_key = getpass(prompt="Enter Encryption key: ")

    snmp_user = (username, authentication_key, encryption_key)

    # load stored machines from pickle_file into dictionary object

    stored_machines = load_stored_machines(pickle_file)

    # create list to store machine objects created from config_check.NewMachine

    pickle_dump_list = []


    # using SNMPv3 poll all defined machines,
    # grab sysName and ccmHistoryRunningLastChanged OIDs

    for values in machines:
        snmp_data = []

        for snmp_oid in (SYSNAME, LASTCHANGE):
            snmp_poll = snmp_extract(snmp_get_oid_v3(values, snmp_user, snmp_oid))
            snmp_data.append(snmp_poll)

        machine_name = snmp_data[0]
        machine_lastchange = snmp_data[1]

        pickle_dump_list.append(NewMachine(machine_name, machine_lastchange))


        # test if polled sysName matches a previously stored device,
        # if match and config change is detected send email alert

        if machine_name in stored_machines:
            alert_obj = stored_machines[machine_name]

            if machine_lastchange > alert_obj.machine_lastchange:
                print "\n{0}: running-config has changed!".format(machine_name)
                email_alert(alert_obj)

            else:
                print "\n{0}: No running-config change detected!".format(machine_name)

        else:
            print "{0}: Not previously found. Saving to {1}".format(machine_name, pickle_file)

    with open(pickle_file, 'w') as pkl_file:
        for list_item in pickle_dump_list:
            pickle.dump(list_item, pkl_file)
Esempio n. 19
0
def main():
    """
    SNMP query all of the interfaces on the pynet-rtr1 using SNMPv3.
    Get the interface description and the in_octets/out_octets
    """
    my_key = getpass(prompt="Auth + Encryption Key: ")

    # SNMPv3 Connection Parameters
    ip_addr = '184.105.247.70'
    a_user = '******'
    auth_key = my_key
    encrypt_key = my_key
    snmp_user = (a_user, auth_key, encrypt_key)
    pynet_rtr1 = (ip_addr, 161)

    print
    print "{:>15} {:>15} {:>15}".format("IfDescr", "IfInOctets", "IfOutOctets")
    for if_index in range(1, 8):
        results = []
        for base_oid in (IFDESCR, IFINOCTETS, IFOUTOCTETS):
            the_oid = base_oid + str(if_index)
            snmp_data = snmp_get_oid_v3(pynet_rtr1, snmp_user, oid=the_oid)
            results.append(snmp_extract(snmp_data))
        print "{:>15} {:>15} {:>15}".format(*results)
    print
Esempio n. 20
0
def get_snmp_data(router, snmp_user, miboid):
    '''
    Get and return snmp data
    '''
    snmp_data = snmp_helper.snmp_extract(
        snmp_helper.snmp_get_oid_v3(router, snmp_user, oid=miboid))
    return snmp_data
Esempio n. 21
0
def main():
    '''
    Create a script that connects to both routers (pynet-rtr1 and pynet-rtr2) and
    prints out both the MIB2 sysName and sysDescr.
    '''
    try:
        ip_addr1 = raw_input("pynet-rtr1 IP address: ")
        ip_addr2 = raw_input("pynet-rtr2 IP address: ")
    except NameError:
        ip_addr1 = input("pynet-rtr1 IP address: ")
        ip_addr2 = input("pynet-rtr2 IP address: ")
    my_key = getpass(prompt="Auth + Encryption Key: ")

    a_user = '******'
    auth_key = my_key
    encrypt_key = my_key

    snmp_user = (a_user, auth_key, encrypt_key)
    pynet_rtr1 = (ip_addr1, 161)
    pynet_rtr2 = (ip_addr2, 161)
    for a_device in (pynet_rtr1, pynet_rtr2):
        print("\n*********************")
        for oid in (SYS_NAME, SYS_DESCR):
            snmp_data = snmp_helper.snmp_get_oid_v3(a_device, snmp_user, oid)
            output = snmp_helper.snmp_extract(snmp_data)
            print(output)
        print("*********************")
    print()
Esempio n. 22
0
def main():
    previous_changed_seconds = 0
    changes = 0
    while (1):
        snmp_output = snmp_helper.snmp_get_oid_v3(DEVICE, SNMP_USER, oid=OID)
        print 'Raw output:', snmp_output
        current_changed_seconds = snmp_helper.snmp_extract(snmp_output)
        print '\nFormatted output:', current_changed_seconds
        print 'changes is', changes
        if (not (int(previous_changed_seconds)
                 == int(current_changed_seconds))):
            if (changes):
                print '\nConfig changed (\#', str(changes), ')', str(
                    int(current_changed_seconds) / 100), 'secs ago'
                message_sender = '*****@*****.**'
                message_subject = 'config changed'
                message_recipient = '*****@*****.**'
                message_content = 'Config of router has recently changed'
                email_result = send_mail(message_recipient, message_subject,
                                         message_content, message_sender)
                if (email_result):
                    print 'Email sent'
                else:
                    print 'Error sending email'
            changes = changes + 1
            previous_changed_seconds = current_changed_seconds
        else:
            print 'Nothing changed:'
            print '  previous_changed_seconds', previous_changed_seconds
            print '  current_changed_seconds', current_changed_seconds
            print '  changes', changes
        time.sleep(310)
Esempio n. 23
0
def get_save_dates(device, user):

    runLastChanged = '1.3.6.1.4.1.9.9.43.1.1.1.0'
    runLastSaved = '1.3.6.1.4.1.9.9.43.1.1.2.0'
    startLastChanged = '1.3.6.1.4.1.9.9.43.1.1.3.0'

    snmp_data = snmp_helper.snmp_get_oid_v3(device, user, runLastChanged)
    rlc_value = snmp_helper.snmp_extract(snmp_data)

    snmp_data = snmp_helper.snmp_get_oid_v3(device, user, runLastSaved)
    rls_value = snmp_helper.snmp_extract(snmp_data)

    snmp_data = snmp_helper.snmp_get_oid_v3(device, user, startLastChanged)
    slc_value = snmp_helper.snmp_extract(snmp_data)

    return rlc_value, rls_value, slc_value
Esempio n. 24
0
def update_data(NEW,description,in_octets,in_packets,out_octets,out_packets,time):
    if time >= 60:
        time = 5
    else:
        time = time + 5
    for name,oid in oids:
        if name == 'ifDescr_fa4':
            snmp_raw = snmp_helper.snmp_get_oid_v3(rtr1,rtr1_snmp,oid=oid)
            snmp_dec = snmp_helper.snmp_extract(snmp_raw)
            description = snmp_dec
        if name == 'ifInOctets_fa4':
            snmp_raw = snmp_helper.snmp_get_oid_v3(rtr1,rtr1_snmp,oid=oid)
            snmp_dec = snmp_helper.snmp_extract(snmp_raw)
            if NEW == True:
                in_octets.insert(0,int(snmp_dec))
            else:
                in_octets.insert(1,int(snmp_dec) - in_octets[0])
                in_octets[0] = int(snmp_dec)
                in_octets = in_octets[:13]
        if name == 'ifInUcastPkts_fa4':
            snmp_raw = snmp_helper.snmp_get_oid_v3(rtr1,rtr1_snmp,oid=oid)
            snmp_dec = snmp_helper.snmp_extract(snmp_raw)
            if NEW == True:
                in_packets.insert(0,int(snmp_dec))
            else:
                in_packets.insert(1,int(snmp_dec) - in_packets[0])
                in_packets[0] = int(snmp_dec)
                in_packets = in_packets[:13]
        if name == 'ifOutOctets_fa4':
            snmp_raw = snmp_helper.snmp_get_oid_v3(rtr1,rtr1_snmp,oid=oid)
            snmp_dec = snmp_helper.snmp_extract(snmp_raw)
            if NEW == True:
                out_octets.insert(0,int(snmp_dec))
            else:
                out_octets.insert(1,int(snmp_dec) - out_octets[0])
                out_octets[0] = int(snmp_dec)
                out_octets = out_octets[:13]
        if name == 'ifOutUcastPkts_fa4':
            snmp_raw = snmp_helper.snmp_get_oid_v3(rtr1,rtr1_snmp,oid=oid)
            snmp_dec = snmp_helper.snmp_extract(snmp_raw)
            if NEW == True:
                out_packets.insert(0,int(snmp_dec))
            else:
                out_packets.insert(1,int(snmp_dec) - out_packets[0])
                out_packets[0] = int(snmp_dec)
                out_packets = out_packets[:13]
    return(description,in_octets,in_packets,out_octets,out_packets,time)
Esempio n. 25
0
def get_the_current_value(device, user):
    '''
    to get the current value of ccmHistoryRunningLastChanged
    and the value of uptime
    to calculate out how many hundredths of seconds did the change happen before NOW
    '''
     
    ccmHistoryRunningLastChanged = '1.3.6.1.4.1.9.9.43.1.1.1.0'
    sysUptime = '1.3.6.1.2.1.1.3.0'
    output = snmp_helper.snmp_get_oid_v3(device, user, ccmHistoryRunningLastChanged)
    last_change = snmp_helper.snmp_extract(output)
    output = snmp_helper.snmp_get_oid_v3(device, user, sysUptime)
    uptime = snmp_helper.snmp_extract(output)
    dvalue = int(uptime) - int(last_change)
    value = (last_change, uptime, dvalue)

    return value
Esempio n. 26
0
def get_int_value(oid):

    snmp_device = ('50.76.53.27', 7961)
    snmp_user = ('pysnmp', 'galileo1', 'galileo1')

    value = int(snmp_extract(snmp_get_oid_v3(snmp_device, snmp_user, oid)))

    return value
Esempio n. 27
0
def get_snmpv3_data(config_update_oids, pynet_rtr1, snmp_user):
    dict_result = {}
    for i, j in config_update_oids:
        snmp_data = snmp_helper.snmp_get_oid_v3(pynet_rtr1, snmp_user, oid=j)
        output = snmp_helper.snmp_extract(snmp_data)
        #print "%s %s"%(i, output)
        dict_result.update({i: output})
    return dict_result
Esempio n. 28
0
def get_int_value(oid):

    snmp_device = ('50.76.53.27',7961)
    snmp_user = ('pysnmp','galileo1','galileo1')
    
    value = int(snmp_extract(snmp_get_oid_v3(snmp_device, snmp_user, oid)))
    
    return value
Esempio n. 29
0
def get_intf_stats():
    count = 0
    global fa4_in_octets,fa4_out_octets,fa4_in_packets,fa4_out_packets
    print("Gathering statistics.  Check back in 1 hour.")
    while count < 6:
        fa4_in_oct_count = int(snmp_extract(snmp_get_oid_v3(router,snmp_user,oid=input_oct)))
        fa4_in_octets.append(fa4_in_oct_count)
        fa4_out_oct_count = int(snmp_extract(snmp_get_oid_v3(router,snmp_user,oid=output_oct)))
        fa4_out_octets.append(fa4_out_oct_count)
        fa4_in_count = int(snmp_extract(snmp_get_oid_v3(router,snmp_user,oid=input_ucast)))
        fa4_in_packets.append(fa4_in_count)
        fa4_out_count = int(snmp_extract(snmp_get_oid_v3(router,snmp_user,oid=output_ucast)))
        fa4_out_packets.append(fa4_out_count)
        count +=1
        time.sleep(10)
    print("Done.  Generating graph.")
    return(fa4_in_octets,fa4_out_octets,fa4_in_packets,fa4_out_packets)
def main():
    snmp_device = (ip_addr, snmp_port_rtr2)
    snmp_user = (user, auth_key, encrypt_key)

    # Check whether time file already exists.
    try:
        with open('time.pkl') as file:
            pass
    except:
        # If time file does not exist, create first time entry.
        snmp_data = snmp_get_oid_v3(snmp_device, snmp_user, oid=runningLastChanged)
        output = snmp_extract(snmp_data)
        # Store time in a pickle file.
        d = open("time.pkl", "wb")
        pickle.dump(output, d)
        d.close()

    # Get last time stored.
    d = open("time.pkl", "rb")
    last_time = pickle.load(d)
    print "Last time: " + last_time

    # Check time of last running config change.
    snmp_data = snmp_get_oid_v3(snmp_device, snmp_user, oid=runningLastChanged)
    output = snmp_extract(snmp_data)
    print "New time: " + output

    # If time of last change greater than stored time, 
    # store the new change time and send email.
    if output > last_time:
        s = float(output)
        t = Decimal(s/100.0)
        time = round(t,2)
        print "Time is now Greater: " + str(time)
        
        # Store time of latest change in a pickle file.
        d = open("time.pkl", "wb")
        pickle.dump(output, d)
        d.close()
        print "New stored value: " + output

        # Send me an email with the time of last change.
        message = "Running config changed at: " + str(time) + "sec"
        email_helper.send_mail(recipient, subject, message, sender)
    else:
        print "Running config has not changed."
Esempio n. 31
0
def get_data(device, user, filename, time_stemp, inboundOID, outboundOID):
    '''
    to get the value of ifInOctets_fa4 and ifOutOctets_fa4
    '''

    data = []
    data.append({})

    data[-1]['time'] = time_stemp

    output = snmp_helper.snmp_get_oid_v3(device, user, inboundOID)
    data[-1]['inbound'] = snmp_helper.snmp_extract(output)

    output = snmp_helper.snmp_get_oid_v3(device, user, outboundOID)
    data[-1]['outbound'] = snmp_helper.snmp_extract(output)
    
    with open(filename, "a") as stream:
        stream.write(yaml.dump(data, default_flow_style = False))
Esempio n. 32
0
def get_the_current_value(device, user):
    '''
    to get the current value of ccmHistoryRunningLastChanged
    and the value of uptime
    to calculate out how many hundredths of seconds did the change happen before NOW
    '''

    ccmHistoryRunningLastChanged = '1.3.6.1.4.1.9.9.43.1.1.1.0'
    sysUptime = '1.3.6.1.2.1.1.3.0'
    output = snmp_helper.snmp_get_oid_v3(device, user,
                                         ccmHistoryRunningLastChanged)
    last_change = snmp_helper.snmp_extract(output)
    output = snmp_helper.snmp_get_oid_v3(device, user, sysUptime)
    uptime = snmp_helper.snmp_extract(output)
    dvalue = int(uptime) - int(last_change)
    value = (last_change, uptime, dvalue)

    return value
Esempio n. 33
0
def get_snmp_conf_time(snmp_conf, snmp_oids):
    snmp_tmp = {}
    for oid_name, oid in snmp_oids:
        snmp_device = (snmp_conf['ip_addr'], int(snmp_conf['snmp_port']))
        snmp_user = (snmp_conf['snmp_user'], snmp_conf['snmp_auth_key'],
                     snmp_conf['snmp_encrypt_key'])
        snmp_tmp[oid_name] = int(
            snmp_extract(snmp_get_oid_v3(snmp_device, snmp_user, oid))) / 100
    return snmp_tmp  # Return dictionary with uptime and run|start time
Esempio n. 34
0
def get_data(device, user, filename, time_stemp, inboundOID, outboundOID):
    '''
    to get the value of ifInOctets_fa4 and ifOutOctets_fa4
    '''

    data = []
    data.append({})

    data[-1]['time'] = time_stemp

    output = snmp_helper.snmp_get_oid_v3(device, user, inboundOID)
    data[-1]['inbound'] = snmp_helper.snmp_extract(output)

    output = snmp_helper.snmp_get_oid_v3(device, user, outboundOID)
    data[-1]['outbound'] = snmp_helper.snmp_extract(output)

    with open(filename, "a") as stream:
        stream.write(yaml.dump(data, default_flow_style=False))
Esempio n. 35
0
def snmp_get(whichrouter, which_oid):
    """
    Get snmp result based on which router and OID
    """
    snmp_data = snmp_helper.snmp_get_oid_v3(whichrouter,
                                            snmp_user,
                                            oid=which_oid)
    snmp_result = int(snmp_helper.snmp_extract(snmp_data))
    return snmp_result
Esempio n. 36
0
def main():
    # pynet-rtr2 (Cisco 881)
    device = ('184.105.247.71', 161)
    snmp_user = ('pysnmp', 'galileo1', 'galileo1')
    ssh_user = ('pyclass', '88newclass')
    recipient = '*****@*****.**'
    sender = '*****@*****.**'
    device_name = snmp_helper.snmp_extract(
        snmp_helper.snmp_get_oid_v3(device, snmp_user, oid=OID_SYSNAME))
    yaml_filename = device_name + '.yml'
    # get running config change timestamp (last_changed_net)
    last_changed_net = snmp_helper.snmp_extract(
        snmp_helper.snmp_get_oid_v3(device, snmp_user, oid=OID_RUN_CHANGED))
    # Load last checked running config timestamp (last_changed_yaml) from YAML file, default to epoc
    try:
        with open(yaml_filename) as f:
            yaml_data = yaml.load(f)
    except EnvironmentError:
        #Yaml file doesn't exist, load some defaults
        yaml_data = {'last_changed': 0, 'config': ''}
    # if last_changed_net > last_changed_yaml, then: get config_net, compare to config_yaml, email diff, store config_net and last_changed_net in yaml file
    if last_changed_net > yaml_data['last_changed']:
        print("Change detected. Getting config from " + device_name + "...")
        config_net = get_ios_config().split('\n')
        config_yaml = yaml_data['config']
        config_diff = list(
            set(config_net).symmetric_difference(set(config_yaml)))
        #Email the difference
        print("Notifying " + recipient + "...")
        subj = 'CHANGE DETECTED: Config on ' + device_name + ' detected at ' + datetime.datetime.fromtimestamp(
            time.time()).strftime('%Y-%m-%d %H:%M:%S')
        message = 'Previous Config Timestamp: ' + str(
            yaml_data['last_changed']) + '\n'
        message += 'Current Config Timestamp: ' + last_changed_net + '\n'
        message += '\nNewly Detected Config: \n'
        message += '\n'.join(config_diff)
        email_helper.send_mail(recipient, subj, message, sender)
        #store the current config and time stamp in yaml file
        print("Storing the current config in " + yaml_filename)
        yaml_data = {'last_changed': last_changed_net, 'config': config_net}
        with open(yaml_filename, 'w') as f:
            f.write(yaml.safe_dump(yaml_data, default_flow_style=False))
    else:
        print("No change detected")
Esempio n. 37
0
def poll(device, oid):
    '''
    This function polls a device for the OID passed in.
    The 'device' variable is a tuple of IP and port.
    '''

    snmp_user = ('pysnmp', 'galileo1', 'galileo1')
    data = snmp_extract(snmp_get_oid_v3((device[1],device[2]),snmp_user, oid, auth_proto='sha', encrypt_proto='aes128', display_errors=True))

    return data
Esempio n. 38
0
 def read_all_oids(self):
     self.oid_values = []
     self.snmp_user = (self.username, self.auth_k, self.encry_k)
     self.dev_tuple = (self.ip_address, self.snmp_port)
     for desc, an_oid, is_count in self.snmp_oids:
         self.snmp_data = snmp_helper.snmp_get_oid_v3(self.dev_tuple,
                                                 self.snmp_user, oid=an_oid)
         self.output = snmp_helper.snmp_extract(self.snmp_data)
         self.oid_values.append((desc, self.output))
     return self.oid_values
Esempio n. 39
0
def getRunningLastChangedV3 (devListTuple, snmpAuthTuple):
    '''
    Given a tuple of device tuples if the format (<IP>, <port>) and an SNMPv3 authentication tuple
    in the format (<username>, <authentication key>, <encryption key>), return a dictionary where
    the key is a device name and the value is a tuple in the format (lastChangeOid, sysUptimeOid).
    '''

    sysNameOid = '1.3.6.1.2.1.1.5.0'
    lastChangeOid = '1.3.6.1.4.1.9.9.43.1.1.1.0'
    sysUptimeOid = '1.3.6.1.2.1.1.3.0'
    rtnDict = dict()

    for aDev in devListTuple:
        devName = snmp_extract(snmp_get_oid_v3(aDev, snmp_user, oid=sysNameOid))
        lastChange = snmp_extract(snmp_get_oid_v3(aDev, snmp_user, oid=lastChangeOid))
        uptime = snmp_extract(snmp_get_oid_v3(aDev, snmp_user, oid=sysUptimeOid))
        rtnDict[devName] = (lastChange, uptime)

    return rtnDict
Esempio n. 40
0
def snmp_poll(dev, user, oid):

	''' 
	PURPOSE: Perform an SNMPv3 poll of a device.
	INPUT: Takes a 'device' object containing IP and SNMP_PORT, 'user' object containing the SNMPv3 credentials, and the 'oid' to be polled.
	OUTPUT: Returns a readable form of the SNMP data.
	'''
	
	snmp_raw = snmp_helper.snmp_get_oid_v3(dev, user, oid)
	
	return snmp_helper.snmp_extract(snmp_raw)
Esempio n. 41
0
def main():
#   sleep_time = int(sys.argv.pop())
#   niter = int(sys.argv.pop())
    sleep_time=300
    niter=14
    ip = "184.105.247.70"
    a_user = '******'
    auth_key = 'galileo1'
    encrypt_key = 'galileo1'
    snmp_user = (a_user, auth_key, encrypt_key)
    pynet_rtr1 = (ip, 161)

    count = 0
    plot_lists = {}
    line_chart_1 = pygal.Line()
    line_chart_2 = pygal.Line()

# Create results dictionary
    for oid in oids:
        plot_lists[oid[0]] = []

    timestamps = []
    while count < niter:
#       timestamps.append(time.ctime().split()[3])
        print "\nCount %d" %count
        for oid in oids:
            pname = oid[0]
            snmp_data = snmp_helper.snmp_get_oid_v3(pynet_rtr1, snmp_user, oid=oid[1])
            output = snmp_helper.snmp_extract(snmp_data)
#           print "OUTPUT=%s" %output
            print "%s  %s %s" %(time.ctime().split()[3], oid[0], output)
            sys.stdout.flush()
            plot_lists[pname].append((output))
        count += 1
        time.sleep(sleep_time)

    timestamps=[0,5,10,15,20,25,30,35,40,45,50,55,60]
# Generate plot
    line_chart_1.title = 'Input/Output Bytes for %s' %plot_lists[oids[0][0]][0]
    line_chart_2.title = 'Input/Output Packets for %s' %plot_lists[oids[0][0]][0]
#   timestamps=addNone(timestamps,10)
#   for oid in oids[1:]:
#       results = [int(res) for res in plot_lists[oid[0]]]
#       print "%s: %s" %(oid[0], delta(results))
#       line_chart.add(oid[0], delta(results))
    print "OIDS=%s" %oids[1:3]
    line_chart_1.x_labels = timestamps
    line_chart_1 = plot_data(oids[1:3],plot_lists,line_chart_1)
    line_chart_1.render_to_file('test1.svg')

    line_chart_2.x_labels = timestamps
    line_chart_2 = plot_data(oids[3:],plot_lists,line_chart_2)
    line_chart_2.render_to_file('test2.svg')
Esempio n. 42
0
def get_data(oid_name, snmp_oid_list, ip_addr, snmp_port, username,
             auth_encr_key):
    router = (ip_addr, snmp_port)
    snmp_user = (username, auth_encr_key, auth_encr_key)
    for OID in snmp_oid_list:
        if OID['OID_NAME'] == oid_name:
            target_OID = OID['OID_VALUE']
            snmp_data = snmp_helper.snmp_get_oid_v3(router, snmp_user,
                                                    target_OID)
            return snmp_helper.snmp_extract(snmp_data)
        else:
            return ""
def check_for_change(snmp_user, device_to_check, oid_to_check, history_to_check):
    """Check device OID. Compares against previous value. Returns True or False if the value
    has changed"""
    with open(history_to_check) as a_file:
        previous_check = json.load(a_file)
    print oid_to_check[1]+str(previous_check)
    snmp_data = snmp_helper.snmp_get_oid_v3(device_to_check, snmp_user, oid_to_check[0])
    output = snmp_helper.snmp_extract(snmp_data)
    print oid_to_check[1]+output
    if output != previous_check:
        with open(history_to_check, "w") as write_history_file:
            json.dump(output, write_history_file)
        return previous_check != output
Esempio n. 44
0
def main():

    IP = '50.76.53.27'
    a_user = '******'
    auth_key = 'galileo1'
    encrypt_key = 'galileo1'
    snmp_port1 = 7961
    snmp_port2 = 8061
    snmp_user = (a_user, auth_key, encrypt_key)
    RUN_LAST_CHANGED = '1.3.6.1.4.1.9.9.43.1.1.1.0'
    SYS_NAME = '1.3.6.1.2.1.1.5.0'
    SYS_UPTIME = '1.3.6.1.2.1.1.3.0'
    pynet_rtr1 = (IP, snmp_port1)
    pynet_rtr2 = (IP, snmp_port2)

    snmp_data = snmp_get_oid_v3(pynet_rtr2, snmp_user, oid=RUN_LAST_CHANGED)
    output = snmp_extract(snmp_data)
    print "RUN_LAST_CHANGED: ", output

    snmp_data = snmp_get_oid_v3(pynet_rtr2, snmp_user, oid=SYS_UPTIME)
    output = snmp_extract(snmp_data)
    print "SYS_UPTIME: ", output
Esempio n. 45
0
def poll(device):
    '''
    Poll the device and return the new data.
    Accepts 'device' which is a tuple of name, ip, and snmp port.
    '''


    p_time = strftime(TIMEF, gmtime())
    poll_temp = []
    for name, oid in sorted(oids.items()):
        poll_temp.append(snmp_extract(snmp_get_oid_v3((device[1],device[2]),snmp_user, oid, auth_proto='sha', encrypt_proto='aes128', display_errors=True)))
    newdata = [poll_temp[1], device[1], p_time, int(poll_temp[2]), int(poll_temp[0])]
    return newdata
Esempio n. 46
0
def main():
    
    snmp_user = ('pysnmp', 'galileo1', 'galileo1')
    pynet_rtr1 = ('184.105.247.70', 161)
    pynet_rtr2 = ('184.105.247.71', 161)
    
    prev_data = get_saved_dicts('devices.pkl')
    
    
    current_data = {}
    
    
    for device in (pynet_rtr1, pynet_rtr2):
        snmp_data = []
        
        for oid in (SYS_NAME, SYS_UPTIME, RUN_LAST_CHANGED):
            try:
                value = snmp_extract(snmp_get_oid_v3(device, snmp_user, oid=oid))
                snmp_data.append(int(value))
            except ValueError:
                snmp_data.append(value)
            
            device_name, uptime, last_changed = snmp_data
            
        
        if device_name in prev_data:
            prev_dev = prev_data[device_name]
            
            if uptime < prev_dev['uptime'] or last_changed < prev_dev['last_changed']
            
                if last_changed < RELOAD_WINDOW:
                    print 'Device reloaded but not changed'
                    current_data['device'] = {'device_name': device_name, 'uptime' = uptime, 'last_changed' = last_changed}
                    
                else:
                
                    print ' Device reloaded and changed'
                    send_notification(current_data[device_name])
                    current_data['device'] = {'device_name': device_name, 'uptime' = uptime, 'last_changed' = last_changed}
            
            elif last_changed > prev_dev['last_changed']
                print ' Device changed'
				send_notification(current_data[device_name])
				current_data['device'] = {'device_name': device_name, 'uptime' = uptime, 'last_changed' = last_changed}				

            elif last_changed == prev_dev['last_changed']
                print ' Device not changed'
				current_data['device'] = {'device_name': device_name, 'uptime' = uptime, 'last_changed' = last_changed}	
		
		else:
			current_data['device'] = {'device_name': device_name, 'uptime' = uptime, 'last_changed' = last_changed}
Esempio n. 47
0
File: E1.py Progetto: vpalacio/p4ne
def main():

    IP = '50.76.53.27'
    a_user = '******'
    auth_key = 'galileo1'
    encrypt_key = 'galileo1'
    snmp_port1 = 7961
    snmp_port2 = 8061
    snmp_user = (a_user, auth_key, encrypt_key)
    RUN_LAST_CHANGED = '1.3.6.1.4.1.9.9.43.1.1.1.0'
    SYS_NAME = '1.3.6.1.2.1.1.5.0'
    SYS_UPTIME = '1.3.6.1.2.1.1.3.0'
    pynet_rtr1 = (IP, snmp_port1)
    pynet_rtr2 = (IP, snmp_port2)

    snmp_data = snmp_get_oid_v3(pynet_rtr2, snmp_user, oid=RUN_LAST_CHANGED)
    output = snmp_extract(snmp_data)
    print "RUN_LAST_CHANGED: ", output
    

    snmp_data = snmp_get_oid_v3(pynet_rtr2, snmp_user, oid=SYS_UPTIME)
    output = snmp_extract(snmp_data)
    print "SYS_UPTIME: ",output
def snmp_wrapper(a_device, oid):
    '''
    snmp wrappers that extracts SNMP information from a_device object

    queries device by OID

    extracts snmp_data

    '''

    snmp_dict = snmp_preprocessor(a_device, oid)

    snmp_data = snmp_get_oid_v3(**snmp_dict)

    return snmp_extract(snmp_data)
Esempio n. 49
0
def main():
    run_time = 0
    while run_time <= 12: 
        snmp_data = snmp_helper.snmp_get_oid_v3(pynet_rtr1, snmp_user, oid=OIDs[1][1])
        inbytes.append(int(snmp_helper.snmp_extract(snmp_data)))
    
        snmp_data = snmp_helper.snmp_get_oid_v3(pynet_rtr1, snmp_user, oid=OIDs[2][1])
        inpkts.append(int(snmp_helper.snmp_extract(snmp_data)))
                
        snmp_data = snmp_helper.snmp_get_oid_v3(pynet_rtr1, snmp_user, oid=OIDs[3][1])
        outbytes.append(int(snmp_helper.snmp_extract(snmp_data)))
    
        snmp_data = snmp_helper.snmp_get_oid_v3(pynet_rtr1, snmp_user, oid=OIDs[4][1])
        outpkts.append(int(snmp_helper.snmp_extract(snmp_data)))
        run_time = run_time + 1
        time.sleep(300)
    line_chart = pygal.Line()
    line_chart.title = 'input/output bytes'
    line_chart.x_labels = ['5','10','15','20','25','30','35','40','45','50','55','60']
    line_chart.add('Inbytes',inbytes)
    line_chart.add('Outbytes',outbytes)
    line_chart.add('InPackets',inpkts)
    line_chart.add('Outpackets',outpkts)
    line_chart.render_to_file('interfacechart.svg')   
Esempio n. 50
0
def snmp_wrapper(a_device, oid):
    '''
    snmp wrappers that extracts SNMP information from a_device object

    queries device by OID

    extracts snmp_data

    '''

    snmp_dict = snmp_preprocessor(a_device, oid)

    snmp_data = snmp_get_oid_v3(**snmp_dict)

    return snmp_extract(snmp_data)
def CheckInterfaceStats(oid, value):
    global in_octets, in_packets, out_octets, out_packets
    snmp_device = (snmpaddr, snmpport)
    snmp_user = (v3uname, v3authkey, v3encrkey)
    snmp_data = snmp_helper.snmp_get_oid_v3(snmp_device, snmp_user, oid, v3authtype, v3encrtype)
    output = snmp_helper.snmp_extract(snmp_data)
    output = int(output)
    if value == "1":
        in_octets.append(output)
    if value == "2":
        in_packets.append(output)
    if value == "3":
        out_octets.append(output)
    if value == "4":
        out_packets.append(output)
def check_for_change(snmp_user, device_to_check, oid_to_check,
                     history_to_check):
    """Check device OID. Compares against previous value. Returns True or False if the value
    has changed"""
    with open(history_to_check) as a_file:
        previous_check = json.load(a_file)
    print oid_to_check[1] + str(previous_check)
    snmp_data = snmp_helper.snmp_get_oid_v3(device_to_check, snmp_user,
                                            oid_to_check[0])
    output = snmp_helper.snmp_extract(snmp_data)
    print oid_to_check[1] + output
    if output != previous_check:
        with open(history_to_check, "w") as write_history_file:
            json.dump(output, write_history_file)
        return previous_check != output
def CheckInterfaceStats(oid, value):
    global in_octets, in_packets, out_octets, out_packets
    snmp_device = (snmpaddr, snmpport)
    snmp_user = (v3uname, v3authkey, v3encrkey)
    snmp_data = snmp_helper.snmp_get_oid_v3(snmp_device, snmp_user, oid,
                                            v3authtype, v3encrtype)
    output = snmp_helper.snmp_extract(snmp_data)
    output = int(output)
    if value == '1':
        in_octets.append(output)
    if value == '2':
        in_packets.append(output)
    if value == '3':
        out_octets.append(output)
    if value == '4':
        out_packets.append(output)
Esempio n. 54
0
def extract_snmp_data_from_devices(a_device):
    '''
    extract SNMP data (SYS_NAME, SYS_UPTIME, RUN_LAST_CHANGED) from each
    device and pack it  in the list called snmp_results []
    '''
    RUN_LAST_CHANGED = '1.3.6.1.4.1.9.9.43.1.1.1.0'
    SYS_NAME = '1.3.6.1.2.1.1.5.0'
    SYS_UPTIME = '1.3.6.1.2.1.1.3.0'
    snmp_results = []
    for oid  in (SYS_NAME, SYS_UPTIME, RUN_LAST_CHANGED):
            try:
                value = snmp_extract(snmp_get_oid_v3(a_device, snmp_user, oid=oid))
                snmp_results.append(int(value))
            except ValueError:
                snmp_results.append(value)
    return snmp_results
Esempio n. 55
0
def poll(device, oid):
    '''
    This function polls a device for the OID passed in.
    The 'device' variable is a tuple of IP and port.
    '''

    snmp_user = ('pysnmp', 'galileo1', 'galileo1')
    data = snmp_extract(
        snmp_get_oid_v3((device[1], device[2]),
                        snmp_user,
                        oid,
                        auth_proto='sha',
                        encrypt_proto='aes128',
                        display_errors=True))

    return data
Esempio n. 56
0
def detect_config_change(ipaddr, port):

#Get HistoryRunningLastChanged
#In the lab environment, I am using the following credentials:

    user_name = 'pysnmp'
    auth_key = 'galileo1'         
    encrypt_key = 'galileo1'

    snmp_user = (user_name, auth_key, encrypt_key)
    snmp_device = (ipaddr, port)
    
    
    history_running_last_changed_set = snmp_get_oid_v3(snmp_device, snmp_user, oid='1.3.6.1.4.1.9.9.43.1.1.1.0', auth_proto='sha',
                    encrypt_proto='aes128', display_errors=True)

    history_running_last_changed = str(history_running_last_changed_set[0])
    history_running_last_changed = history_running_last_changed.split('=', 1)[1]
    history_running_last_changed = int(history_running_last_changed.strip())
    print history_running_last_changed
    router_name = snmp_device[0]
                    
    #check the stored file
    while True:
        try:
            f = open("router_config_changes.pkl", "rb")
            router_changetime = pickle.load(f)
            break
        except:
            print " read failed "
            f = open("router_config_changes.pkl", "wb")
            pickle.dump([router_name, 0], f)
            
    #If HistoryRunningLastChanged is greater then send email with router name plus HistoryRunningLastChanged
    time = router_changetime[1]
    if history_running_last_changed > time: 
        difference = history_running_last_changed - time
        my_message = "Network node " + router_changetime[0] + " configuration has changed"
        send_mail("*****@*****.**", "alert", my_message, "*****@*****.**")      
    
    #Save HistoryRunningLastChanged to stored_time_of_last_change   
        router_changetime = [router_name, history_running_last_changed]
        f = open("router_config_changes.pkl", "wb")
        pickle.dump(router_changetime, f)
    
    #cleanup
    f.close()
def make_decision(device, user):
    ''' This is where we compare current time to saved time and determine
     if it has changed , if it has we send an email'''

    sysuptime = get_sys_uptime(device, user)

    snmp_data = snmp_get_oid_v3(device, user, oid=RUN_LAST_CHANGED)
    #current_run_variable = snmp_extract(snmp_data)
    prev_run_variable = read_network_device()

    if sysuptime > prev_run_variable:
        send_email()
        print 'router config has changed , email sent'
    else:
        print 'no change in the config of device under test'

    return sysuptime
def CheckConfig():
	global timestamp
	snmp_device = (snmpaddr, snmpport)
	snmp_user = (v3uname, v3authkey, v3encrkey)
	snmp_data = snmp_helper.snmp_get_oid_v3(snmp_device, snmp_user, oid1, v3authtype, v3encrtype)
	output = snmp_helper.snmp_extract(snmp_data)
	if bool(timestamp) == False:
		timestamp.append(output)
		print '\nWe have begun monitoring this device for configuration changes.'
		print '%s %s' % ('The timestamp for the device is currently: ', output)
		print 'We will check the device again in 5 minutes.\n'
	elif timestamp[0] != '':
		if output == timestamp[0]:
			print 'The configuration has not changed in the last 5 minutes.'
			print '%s %s' % ('The timestamp for the device is currnetly: ', output)
			print 'We will check the device again in 5 minutes.\n'
		elif output != timestamp[0]:
			timestamp[0] = output
			print 'The configuation has changed.'
			print 'Sending email alert and checking device again in 5 minutes.\n'
			email_helper.send_mail(recipient, subject, message, sender)
Esempio n. 59
0
def snmp_get_v3(device, oid, valueonly=False):
    """
	Params:
		device : dict : a device entry
	Returns:
		A tuple containing the hostname and the snmp value
	"""

    print device

    snmp_result = snmp_get_oid_v3(
        (device["ip_address"], device["snmp_port"]),
        (device["snmp_username"], device["snmp_auth_key"], device["snmp_encrypt_key"]),
        oid,
    )

    snmp_value = snmp_extract(snmp_result)

    if valueonly:
        return snmp_value
    else:
        return (device["hostname"], snmp_value)