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)
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)
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 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
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)
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
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 ''
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)
def main(): """ Returns the System Hostname and Device Description using SNMP """ my_hosts = [{ 'ip_addr': '50.76.53.27', 'port': 7961, 'community': 'galileo' }, { 'ip_addr': '50.76.53.27', 'port': 8061, 'community': 'galileo' }] for host in my_hosts: oid = '1.3.6.1.2.1.1.5.0' my_device = (host['ip_addr'], host['community'], host['port']) snmp_data = snmp_get_oid(my_device, oid=oid) output = snmp_extract(snmp_data) print "Hostname:" print output + "\n" oid = '1.3.6.1.2.1.1.1.0' snmp_data = snmp_get_oid(my_device, oid=oid) output = snmp_extract(snmp_data) print "System Description:" print output print "-" * 80 print "\n"
def main(): ipaddr = '50.76.53.27' for i in (7961, 8061): print i,":\n"; print "name >>> ",snmp_helper.snmp_extract(snmp_helper.snmp_get_oid([ipaddr, "galileo", i], '.1.3.6.1.2.1.1.5.0')) print "sysdescr >>> ",snmp_helper.snmp_extract(snmp_helper.snmp_get_oid([ipaddr, "galileo", i], '.1.3.6.1.2.1.1.1.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()
def main(): ''' ''' DEBUG = False COMMUNITY_STRING = 'secret' IP = '1.1.1.1' my_devices = { "Device1": (IP, COMMUNITY_STRING, 7061), "Device2": (IP, COMMUNITY_STRING, 8061), } #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' sys_uptime_oid = '1.3.6.1.2.1.1.3.0' for device_name, snmp_device in my_devices.items(): # Gather data from device snmp_data = snmp_get_oid(snmp_device, oid=sys_uptime_oid) sys_uptime = snmp_extract(snmp_data) uptime_hours = convert_uptime_hours(sys_uptime) snmp_data = snmp_get_oid(snmp_device, oid=ccmHistoryRunningLastChanged) last_run_change = int(snmp_extract(snmp_data)) snmp_data = snmp_get_oid(snmp_device, oid=ccmHistoryStartupLastChanged) last_start_save = int(snmp_extract(snmp_data)) # Determine whether run-start are in sync run_save_status = determine_run_start_sync_state(last_run_change, last_start_save) # Display Output print "\nDevice = %s" % device_name print "Current Uptime = %.1f hours" % uptime_hours if DEBUG: print "Run change time = %s" % last_run_change print "Last save time = %s" % last_start_save # check for a reboot and no save if not(last_start_save): print "This device has never been saved since the last reboot" else: if run_save_status: print "Running config has been saved" else: print "Running config not saved" print
def get_router_info(router_info,SYSNAME,SYSDESC): snmp_data = snmp_get_oid(router_info,oid=SYSNAME) router = snmp_extract(snmp_data) print "Router: %s" % router snmp_data = snmp_get_oid(router_info,oid=SYSDESC) output = snmp_extract(snmp_data) print "SYSDESC: %s" % output
def main(args): parser = OptionParser() parser.add_option('-c', '--community', default='public', help='community string') options, args = parser.parse_args() for arg in args: host, port = arg.split(':') device = (host, options.community, port) for name, oid in OIDS.iteritems(): print snmp_extract(snmp_get_oid(device, oid=oid))
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)
def main(): ipaddr = '50.76.53.27' for i in (7961, 8061): print i, ":\n" print "name >>> ", snmp_helper.snmp_extract( snmp_helper.snmp_get_oid([ipaddr, "galileo", i], '.1.3.6.1.2.1.1.5.0')) print "sysdescr >>> ", snmp_helper.snmp_extract( snmp_helper.snmp_get_oid([ipaddr, "galileo", i], '.1.3.6.1.2.1.1.1.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
def getSnmpInfo(router,comm): rtr_ip = '50.76.53.27' if router == "rtr1": snmp_port = 7961 else: snmp_port = 8061 device = (rtr_ip,comm,snmp_port) rtr_name = snmp_get_oid(device,oid='.1.3.6.1.2.1.1.5.0',display_errors=True) rtr_desc = snmp_get_oid(device,oid='.1.3.6.1.2.1.1.1.0',display_errors=True) name_output = snmp_extract(rtr_name) desc_output = snmp_extract(rtr_desc) return(name_output,desc_output)
def main(): sysName = '.1.3.6.1.2.1.1.5.0' sysDescr = '.1.3.6.1.2.1.1.1.0' rtr1 = ('184.105.247.70', COMMUNITY, SNMP_PORT) rtr2 = ('184.105.247.71', COMMUNITY, SNMP_PORT) pynet.hr("pynet-rtr1") print('SysName: ' + snmp_extract(snmp_get_oid(rtr1, oid=sysName))) print('SysDescr: ' + snmp_extract(snmp_get_oid(rtr1, oid=sysDescr))).splitlines()[0] pynet.hr("pynet-rtr2") print('SysName: ' + snmp_extract(snmp_get_oid(rtr2, oid=sysName))) print('SysDescr: ' + snmp_extract(snmp_get_oid(rtr2, oid=sysDescr))).splitlines()[0]
def get_network_status(): """ Grabs network status (via SNMP for now) and creates the 'speech_output' """ session_attributes = {} card_title = "Network Status" # creating a few lists to write things to keys = [] values = [] list_offline = [] # community_string and snmp_port are set under global variables device = ('snmp.meraki.com', community_string, snmp_port) # snmp_data1 is the list of devNames in the SNMP get response # snmp_helper is imported on line 25, see snmp_helper.py in the example snmp_data1 = snmp_helper.snmp_get_oid(device, oid='.1.3.6.1.4.1.29671.1.1.4.1.2', display_errors=True) # snmp_data2 is the 0 or 1 value that comes back from this OID indicating # the device's online/offline status (0 = offline, 1 = online) snmp_data2 = snmp_helper.snmp_get_oid(device, oid='.1.3.6.1.4.1.29671.1.1.4.1.3', display_errors=True) """ create a dictionary of device names and their online/offline status. the following lines clean up the snmp responses in snmp_data1 and snmp_data2 individually, then add the sanitized data points to dict_status (snmp 'devName' and '0' or '1' for the status) """ for i in snmp_data1: k = snmp_helper.snmp_extract(i) keys.append(k) for j in snmp_data2: m = snmp_helper.snmp_extract(j) values.append(m) # create a new dictionary 'dict_status' with the combined name and status dict_status = dict(zip(keys, values)) # Now iterate through dict_status to capture offline devices for key in dict_status: value = dict_status[key] if value == '0': # below, 'devName' of offline devices (devStatus = 0) is appended to list_offline list_offline.append(key) else: # skip over devices which are not offline (any value other than 0) continue # Finally, count the length of 'list_offline' to get the number of offline # devices and read back each name in the list. # The extra spaces around the comma help Alexa read the names back clearly. # Adjustments may need to be made to fine tune the response. speech_output = "{0} devices are offline, {1}. would you like me to dispatch a technician ?".format( len(list_offline), " , ".join(list_offline)) reprompt_text = "" should_end_session = True return build_response(session_attributes, build_speechlet_response( card_title, speech_output, reprompt_text, should_end_session))
def main(): ''' Using SNMP Write a program that detects if the running configuration has been changed but not saved to startup-config. ''' ip_addr = '50.242.94.227' my_devices = { "pynet_rtr1": (ip_addr, COMMUNITY_STRING, 7961), "pynet_rtr2": (ip_addr, COMMUNITY_STRING, 8061), } sys_uptime_oid = '1.3.6.1.2.1.1.3.0' for device_name, snmp_device in my_devices.items(): # Gather data from device snmp_data = snmp_get_oid(snmp_device, oid=sys_uptime_oid) sys_uptime = snmp_extract(snmp_data) uptime_hours = convert_uptime_hours(sys_uptime) snmp_data = snmp_get_oid(snmp_device, oid=OID_RUN_LAST_CHANGED) last_run_change = int(snmp_extract(snmp_data)) snmp_data = snmp_get_oid(snmp_device, oid=OID_START_LAST_CHANGED) last_start_save = int(snmp_extract(snmp_data)) # Determine whether run-start are in sync run_save_status = determine_run_start_sync_state(last_run_change, last_start_save) # Display output print "\nDevice = %s" % device_name print "Current Uptime = %.1f hours" % uptime_hours if DEBUG: print "Run change time = %s" % last_run_change print "Last save time = %s" % last_start_save # Check for a reboot and no save if not last_start_save: print 'This device has never been saved since the last reboot' else: if run_save_status: print 'Running config has been saved' else: print 'Running config not saved' print
def check_routers(self): timestamp = int(time.time()) if DEBUG: print("My time is: %s" % time.ctime(timestamp)) for router in self.router_list: routerRebooted = False routerTuple = (router['ip_addr'], router['community'], router['port']) routerUptimeOIDData = snmp_helper.snmp_get_oid( routerTuple, SYSUPTIME_OID) routerUptime = int( float(snmp_helper.snmp_extract(routerUptimeOIDData)) / 100) routerRebootTime = timestamp - routerUptime lastConfigChangeSecondsOIDData = snmp_helper.snmp_get_oid( routerTuple, RUNNINGLASTCHANGED_OID) lastConfigChangeSeconds = int( float(snmp_helper.snmp_extract(lastConfigChangeSecondsOIDData)) / 100) runningLastChangedTime = routerRebootTime + lastConfigChangeSeconds if DEBUG: print( "Router: %s uptime: %s reboot time: %s last config change seconds: %s running last changed time %s" % (router['router'], routerUptime, time.ctime(routerRebootTime), lastConfigChangeSeconds, time.ctime(runningLastChangedTime))) if len(self.state) == 0: self.state['lastRebootTime'] = {} self.state['lastConfigChangeTime'] = {} if router['router'] not in self.state['lastRebootTime'].keys(): self.state['lastRebootTime'][ router['router']] = routerRebootTime self.state['lastConfigChangeTime'][ router['router']] = runningLastChangedTime if routerRebootTime > self.state['lastRebootTime'][ router['router']]: routerRebooted = True self.state['lastRebootTime'][ router['router']] = routerRebootTime if runningLastChangedTime > self.state['lastConfigChangeTime'][ router['router']]: if not routerRebooted or (lastConfigChangeSeconds > ROUTER_REBOOT_SECONDS): self.__send_email_alert(router['router'], runningLastChangedTime) self.state['lastConfigChangeTime'][ router['router']] = runningLastChangedTime self.__dump_state()
def get_snmp_info(device_ip): COMMUNITY_STRING = 'galileo' SNMP_PORT = 161 IP = device_ip SYSNAME = '1.3.6.1.2.1.1.5.0' SYSDESCR = '1.3.6.1.2.1.1.1.0' device = (IP, COMMUNITY_STRING, SNMP_PORT) snmp_sysname_data = snmp_helper.snmp_get_oid(device, oid=SYSNAME) snmp_sysdescr_data = snmp_helper.snmp_get_oid(device, oid=SYSDESCR) sysname_output = snmp_helper.snmp_extract(snmp_sysname_data) sysdescr_output = snmp_helper.snmp_extract(snmp_sysdescr_data) print sysname_output print sysdescr_output
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)
def main(): rtr1 = (IP, COMMUNITY, 7961) rtr2 = (IP, COMMUNITY, 8061) rtr1_sysname = snmp_helper.snmp_get_oid(rtr1, SYSNAME_OID) rtr1_sysdescr = snmp_helper.snmp_get_oid(rtr1, SYSDESCR_OID) rtr2_sysname = snmp_helper.snmp_get_oid(rtr2, SYSNAME_OID) rtr2_sysdescr = snmp_helper.snmp_get_oid(rtr2, SYSDESCR_OID) print "rtr1 sysname: %s\n" % snmp_helper.snmp_extract(rtr1_sysname) print "rtr1 sysdescr: %s\n" % snmp_helper.snmp_extract(rtr1_sysdescr) print "rtr2 sysname: %s\n" % snmp_helper.snmp_extract(rtr2_sysname) print "rtr2 sysdescr: %s\n" % snmp_helper.snmp_extract(rtr2_sysdescr)
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: ") community_string = getpass.getpass(prompt="Community string: ") # The library requires this type of tuple. # SYNTAX: (ip_addr, comm_string, SNMP default port) pynet_rtr1 = (ip_addr1, community_string, 161) pynet_rtr2 = (ip_addr2, community_string, 161) for device in [pynet_rtr1, pynet_rtr1]: print("\n************************") for oid in [SYS_NAME, SYS_DESCR]: snmp_data = snmp_get_oid(device, oid=oid) output = snmp_extract(snmp_data) print(output) print("\n************************") print()
def poll_print_oid(self, oid): # Combines both snmp_get_oid and snmp_extract into one class method self.oid = oid self.a_device = (self.ip_address, self.community, self.snmp_port) self.snmp_data = snmp_get_oid(self.a_device, self.oid) self.output = snmp_extract(self.snmp_data) return self.output
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
def snmp_get(router, oids): data = {} for oid_name, oid in oids.items(): data['router_ip'] = router[0] data[oid_name] = snmp_extract(snmp_get_oid(router, oid)) print(data) return data
def snmp_print_sysdescr(l_ip, l_port='161', l_community='public'): ''' Print snmp sysdescr ''' conn_dev = (l_ip, l_community, l_port) snmp_data = snmp_extract(snmp_get_oid(conn_dev, oid='1.3.6.1.2.1.1.1.0')) return snmp_data
def get_cell_status(): # community_string and snmp_port are set under global variables device = ('snmp.meraki.com', community_string, snmp_port) # devCellularStatus snmp_data = snmp_helper.snmp_get_oid(device, oid='.1.3.6.1.4.1.29671.1.1.4.1.14', display_errors=True) for row in snmp_data: # for each response with 'Active' cellular status, append the devName to cell_active_list if row[0][1] == 'Active': # dup of the original function to extract [0][0] vs. [0][1] extract_oid = snmp_helper.snmp_extract2(row) # replace the front of the oid to create a new oid for name lookup name_oid = extract_oid.replace('SNMPv2-SMI::enterprises.29671.1.1.4.1.14', '.1.3.6.1.4.1.29671.1.1.4.1.2') # lookup and extract the devName of the device with 'Active' cellular status # dup of the original function that issues a get vs. getNext snmp_name = snmp_helper.snmp_get_oid2(device, oid=name_oid, display_errors=True) dev_name = snmp_helper.snmp_extract(snmp_name) # append devName to cell_active_list cell_active_list.append(dev_name) # write devName to CSV csv_row_text = format(str(dev_name)) csv_writer.writerow([csv_row_text]) print "writing to CSV: %s" % csv_row_text # for watching live else: # ignoring anything without 'Active' status continue return cell_active_list
def main(args): parser = OptionParser() parser.add_option('-c', '--community', default='public', help='community string') parser.add_option('-D', '--debug', action='store_true', help='be verbose') options, args = parser.parse_args() data = {} for arg in args: host, port = arg.split(':') device = (host, options.community, port) data[arg] = {} for name, oid in OIDS.iteritems(): data[arg][name] = snmp_extract(snmp_get_oid(device, oid=oid)) for host in data: # From the mib: # If the value of ccmHistoryRunningLastChanged is greater than # ccmHistoryRunningLastSaved, the configuration has been # changed but not saved. if options.debug: print data[host] if data[host]['runningLastChanged'] > data[host]['runningLastSaved']: print "%s config modified (%s), but not saved (%s)" % ( host, data[host]['runningLastChanged'], data[host]['startupLastChanged'] )
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)
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()
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
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
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)
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))
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
def snmp_get(snmp_data, device): access_details = (device['IP'], COMMUNITY_STRING, SNMP_PORT) snmp_results = snmp_helper.snmp_get_oid(access_details, snmp_data['OID']) output = snmp_helper.snmp_extract(snmp_results) print("For "+device['name']+" the "+snmp_data['name']+" is "+'\n') print(output) print('\n')
def main(): for p in IP: for i in oid: a_device = (p, COMMUNITY_STRING, SNMP_PORT) snmp_data = snmp_get_oid(a_device, oid=i) output = snmp_extract(snmp_data) print output +"\n"
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
def main(): for p in IP: for i in oid: a_device = (p, COMMUNITY_STRING, SNMP_PORT) snmp_data = snmp_get_oid(a_device, oid=i) output = snmp_extract(snmp_data) print output + "\n"
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: ") community_string = getpass.getpass(prompt="Community string: ") pynet_rtr1 = (ip_addr1, community_string, 161) pynet_rtr2 = (ip_addr2, community_string, 161) for a_device in (pynet_rtr1, pynet_rtr2): print("\n*********************") for the_oid in (SYS_NAME, SYS_DESCR): snmp_data = snmp_helper.snmp_get_oid(a_device, oid=the_oid) output = snmp_helper.snmp_extract(snmp_data) print(output) print("*********************") print()
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)
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)
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."
def main(): '''' Create a script that connects to both routers (pynet-rtr1 and pynet-rtr2) and prints out both the MIB2 sysName and sysDescr. ''' a_device = (ip_addr, comm_string, snmp_port) snmp_sys_name = snmp_get_oid(a_device, oid='1.3.6.1.2.1.1.5.0') snmp_sys_desc = snmp_get_oid(a_device, oid='1.3.6.1.2.1.1.1.0') output_sys_name = snmp_extract(snmp_sys_name) output_sys_desc = snmp_extract(snmp_sys_desc) print '\nDevice Name:' print output_sys_name print '\nSystem Description:' print output_sys_desc + '\n'
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 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
def snmp_query(node_info, oid): '''Query for OID on node - all necessary parameters should be part of node_info data structure ''' snmp_output = snmp_get_oid(node_info, oid) output = snmp_extract(snmp_output) return output
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
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
def main(): t_handler = t_login("pyclass", "88newclass", "", "184.105.247.70") print(t_command(t_handler, "term len 0").decode('ascii')) print(t_command(t_handler, "sh ver").decode('ascii')) t_handler.close snmp_data = snmp_helper.snmp_get_oid(a_device, OID) output = snmp_helper.snmp_extract(snmp_data) print(output)
def snmp_getuptime(ip, communitystring, port): global uptime device = (ip, communitystring, port) uptime = int( snmp_extract( snmp_get_oid(device, oid=".1.3.6.1.2.1.1.3.0", display_errors=True))) / 60480000 return uptime