def getRoutingTable(ipRouter, router=None): session = Session(hostname=ipRouter, community=COMMUNITY, version=2) # crear sessio per connectar amb el router networks = session.walk('IP-FORWARD-MIB::ipCidrRouteDest') # xarxes desti nexthop = session.walk( 'IP-FORWARD-MIB::ipCidrRouteNextHop') # nexthop per la xarxa desti tipus = session.walk('IP-FORWARD-MIB::ipCidrRouteType') # tipus de ruta masks = session.walk( 'IP-FORWARD-MIB::ipCidrRouteMask') # mascara de la xarxa desti table = list() for x, y, z, n in zip(networks, masks, nexthop, tipus): # combinem linea a linea la informacio rebuda route = RouteEntry(x.value, y.value, z.value) # creem un objecte ruta a partir de la informacio anterior router.addRoute(route) # afegim aquesta ruta al router tipus = '' # descodifiquem el valor rebut a llenguatge huma if (n.value == '1'): tipus = 'Other' elif (n.value == '2'): tipus = 'Reject' elif (n.value == '3'): tipus = 'Local' elif (n.value == '4'): tipus = 'Remote' table.append((x.value, y.value, z.value, tipus)) # afegim la informacio anterior a la taula a mostrar print 'RoutingTable: ' headers = ["Network", "Mask", "Nexthop", "Type"] # definim capcalera taula print tabulate(table, headers, tablefmt="fancy_grid") # printar taula
def last_down_cause(olt, comnty, pon=None): """ Retorna o motivo da última queda de cada onu da pon passada. """ try: # Tentando criar a sessão snmp session = Session(hostname=olt, community=comnty, version=2) except: # algum parâmetro errado print(f"\nAlgum erro ao tentar criar uma sessão, antes mesmo de fazer o snmp walk!\nOLT: {olt}\nCommunity: {comnty}") sys.exit() try: # Tentando realizar o snmpwalk if pon: # pon específica resultado = session.walk(f'1.3.6.1.4.1.2011.6.128.1.1.2.46.1.24.{pon}') # oid que retorna descrições else: # olt inteira resultado = session.walk('1.3.6.1.4.1.2011.6.128.1.1.2.46.1.24') # oid que retorna descrições except: # timeout print("Não foi possível realizar o snmp walk do last down cause. Aguarde alguns instantes e tente novamente. Saindo...") sys.exit() resultados_value = [] for res in resultado: if res.value == '2': resultados_value.append("___LOS___") elif res.value == '13': resultados_value.append("dying-gasp") elif res.value == '-1': resultados_value.append("info_zerada") else: resultados_value.append("cond_estranha") return resultados_value # retorna uma lista com as descrições
def make_telnet_connection(): host = input("Ingresa la dirección del servidor TELNET: ") user = input("Ingresa el usuario: ") password = input("Ingresa la contraseña: ") start_time = int(time.time()) try: tn = telnetlib.Telnet(host) tn.read_until(b"User: "******"\n") if password: tn.read_until(b"Password: "******"\n") tn.interact() print(tn.read_all().decode('ascii')) except Exception as e: print(e) final_time = int(time.time()) print("\nTiempo de interacción: " + str(final_time - start_time)) session = Session(hostname='localhost', community="MacCommunity", version=2) trafico_recibido = session.walk('1.3.6.1.2.1.2.2.1.10') trafico_enviado = session.walk('1.3.6.1.2.1.2.2.1.16') print("Trafico recibido: " + str(trafico_recibido)) print("Trafico enviado: " + str(trafico_enviado))
def potencia(olt, comnty, pon=None, tipo='onu'): """ Retorna o sinal rx de cada onu na pon passada.""" # Saída é meiia estranha :/ ex: ['HWTC\x84½\x00\x9a', 'HWTC¶\x9eD\x9c'] sinais_snmp = [] try: # Tentando criar a sessão snmp session = Session(hostname=olt, community=comnty, version=2) except: # algum parâmetro errado print(f"\nAlgum erro ao tentar criar uma sessão, antes mesmo de fazer o snmp walk!\nOLT: {olt}\nCommunity: {comnty}") sys.exit() try: # Tentando realizar o snmpwalk if pon: # pon específica if tipo == 'onu': sinais_snmp = session.walk(f'1.3.6.1.4.1.2011.6.128.1.1.2.51.1.4.{pon}') # oid que retorna Potência RX das ONUs elif tipo == 'olt': sinais_snmp = session.walk(f'.1.3.6.1.4.1.2011.6.128.1.1.2.51.1.6.{pon}') # oid que retorna Potência TX das ONUs else: print(f'Para consutar a potência, escolha apenas "onu" ou "olt". Você escolheu: {tipo}') else: # olt inteira if tipo == 'onu': sinais_snmp = session.walk('1.3.6.1.4.1.2011.6.128.1.1.2.51.1.4') # oid que retorna Potência RX das ONUs elif tipo == 'olt': sinais_snmp = session.walk('.1.3.6.1.4.1.2011.6.128.1.1.2.51.1.6') # oid que retorna Potência TX das ONUs else: print(f'Para consutar a potência, escolha apenas "onu" ou "olt". Você escolheu: {tipo}') except: # timeout print("Não foi possível realizar o snmp walk das potências. Aguarde alguns instantes e tente novamente. Saindo...") sys.exit() sinais = [] for sinal in sinais_snmp: temp = f'{int(sinal.value) / 100:.2f}' sinais.append(str(temp)) return sinais
def ipsla_search(data): # Retrieving SNMP config from yaml f = open('config.yaml', 'r') config = yaml.load(f) f.close() # Check Version of SNMP Used if data['snmp_version'] == '2': message = "SNMP Version 2 Is not implemented yet" message_category = 'error' return [], [], [], message, message_category elif data['snmp_version'] == '3': # Create an SNMP session to be used for all our requests snmp_session = Session(retries=config['snmp']['retries'], timeout=config['snmp']['timeout'], hostname=data['hostname'], version=int(data['snmp_version']), security_level=data['security_level'], security_username=data['security_username'], auth_protocol=data['auth_protocol'], auth_password=data['auth_password'], privacy_protocol=data['privacy_protocol'], privacy_password=data['privacy_password']) try: # Perform an SNMP walk to retrieve all the ipsla's configured and types ipsla_types = snmp_session.walk('1.3.6.1.4.1.9.9.42.1.2.1.1.4') # Handle timeout error except EasySNMPTimeoutError: message = "Timeout connecting to host {host}".format(host=data['hostname']) message_category = 'error' return [], [], [], message, message_category # Handle Connection error except EasySNMPConnectionError: message = "Error connecting to host {host}".format(host=data['hostname']) message_category = 'error' return [], [], [], message, message_category # Handle OID Problem, device not supported maybe? except EasySNMPUnknownObjectIDError: message = "Device {host} not supported".format(host=data['hostname']) message_category = 'error' return [], [], [], message, message_category # Perform an SNMP walk to retrieve all the Tags for the ipsla's ipsla_tags = snmp_session.walk('1.3.6.1.4.1.9.9.42.1.2.1.1.12') # Create lists for indexes and types indexes = [] types = [] tags = [] i = 0 for ipsla in ipsla_types: indexes.append(ipsla.oid_index) types.append(ipsla.value) tags.append(ipsla_tags[i].value) i += 1 message = 'Connection to host {host} successful'.format(host=data['hostname']) message_category = 'success' return indexes, types, tags, message, message_category
def getinfoprinter(printer): session = Session(hostname=printer, community="public", version=2) print('Informacion de la impresora') print(str(session.walk( '1.3.6.1.2.1.43.10.2'))) # Imprime el numero de paginas impresas print(str(session.walk( '1.3.6.1.2.1.43.11.1.1.7'))) # Imprime los niveles de tinta print(str(session.walk( '1.3.6.1.2.1.25.3.5.1.1'))) # Imprime el estado de la impresora
def handle(self, *args, **options): session = Session(hostname='192.168.200.101', community='public', version=2, ) try: for i in session.walk(MIBS.get('interfaces_list')): print(i) print('WWWWWWWWWWWWWWWWWWWWWWWWWW') print(session.walk(MIBS.get('all_onu_signal'))) except EasySNMPTimeoutError: print('ERROR')
def get_lldp_a3_dlink(a3_arg, element_arg, cfg_ini): #-----------------------------------Первый A3----------------------------------------------------------------------- session_a3_1 = Session(hostname=a3_arg, community='ntcore', version=2) # Достаем Agg_Ports oid_lldp = session_a3_1.walk('.1.2.840.802.10006.300.43.1.2.1.1.24') for item_agg in oid_lldp: #Проверяем порт на участие в Agg if item_agg.value == u'1': tmp_parse = [] for q in str(item_agg.oid).split('.'): tmp_parse.append(q) ports_1.append(str(tmp_parse[12])) #Ищем элемент на портах и линк А3-А3 session_a3_1 = Session(hostname=a3_arg, community='ntcore', version=2) oid_lldp = session_a3_1.walk('.1.0.8802.1.1.2.1.4.1.1.9') for item in oid_lldp: if element_arg in str(item.value) or cfg_ini['A3'][a3_arg] in str(item.value).lower(): tmp_parse = [] for q in str(item.oid).split('.'): tmp_parse.append(q) ports_1.append(str(tmp_parse[12])) print (a3_arg) print("Элемент " + element_arg + " найден на порту: " + str(ports_1)) print ('--------------------------------------------------------') #-----------------------------------Второй A3----------------------------------------------------------------------- session_a3_2 = Session(hostname=cfg_ini['A3'][a3_arg], community='ntcore', version=2) # Достаем Agg_Ports oid_lldp = session_a3_2.walk('.1.2.840.802.10006.300.43.1.2.1.1.24') for item_agg in oid_lldp: #Проверяем порт на участие в Agg if item_agg.value == u'1': tmp_parse = [] for q in str(item_agg.oid).split('.'): tmp_parse.append(q) ports_2.append(str(tmp_parse[12])) #Ищем элемент на портах и линк А3-А3 session_a3_2 = Session(hostname=cfg_ini['A3'][a3_arg], community='ntcore', version=2) oid_lldp = session_a3_2.walk('.1.0.8802.1.1.2.1.4.1.1.9') for item in oid_lldp: if element_arg in str(item.value) or a3_arg in str(item.value).lower(): tmp_parse = [] for q in str(item.oid).split('.'): tmp_parse.append(q) ports_2.append(str(tmp_parse[12])) print (cfg_ini['A3'][a3_arg]) print("Элемент " + element_arg + " найден на порту: " + str(ports_2)) print ('--------------------------------------------------------') return (ports_1, ports_2)
def main(): """ The main loop! """ snmp_session = Session(hostname='10.99.1.11', community='l1ver3ad', version=2) interface_descrs = snmp_session.walk('.1.3.6.1.2.1.2.2.1.2') interface_changed = snmp_session.walk('.1.3.6.1.2.1.2.2.1.9') for iface in interface_descrs: interface_index = int(iface.oid.rsplit('.', 1)[1]) try: date_changed = datetime.datetime.now() - datetime.timedelta(seconds=int(interface_changed[interface_index].value)) print "%i %s %s %s" %(interface_index, iface.value, interface_changed[interface_index].value, date_changed) except IndexError: break
class SNMPManager(): _session_ = None _snmp_host_ = None def __init__(self, snmp_host, community, version): self._snmp_host_ = snmp_host self._session_ = Session(hostname=snmp_host, community=community, version=version, use_long_names=True, use_sprint_value=True) def is_alive(self): try: val = self._session_.get('SNMPv2-MIB::sysName.0') if val.value: return True except: snmp_logger.error("Unable to reach snmp host %s" % self._snmp_host_, exc_info=True) pass return False def walk_oid(self, oid_name): try: return self._session_.walk(oid_name) except EasySNMPTimeoutError as timeout: snmp_logger.error("SNMP Timeout Error,", exc_info=True) snmp_logger.info("No values will be collected") return []
def main(): parser = argparse.ArgumentParser(description=description) parser.add_argument("-H", "--hostname", help="IP Address / Hostname to check [REQUIRED]",type=str, required=True) parser.add_argument("-c", "--community",help="SNMP Community (default 'public')",type=str,default='public') args = parser.parse_args() hostname = args.hostname comm = args.community session = Session(hostname=hostname, community=comm, version=2) try: item = session.walk(ifName) except: sys.exit('\nSNMP PROBLEM host '+hostname+" check IP and COMMUNITY\n") # get uptime to calculate last change uptime = session.get(sysUpTime).value print '\nHOST\t'+hostname print "\nUPTIME\t"+str(timedelta(seconds=(int(uptime)/100)))+"\n" # port names to include or ignore to filter useless values include= ('ethernet') ignore = ('Vl','vlan','VLAN','VLAN-','Trk','lo','oobm','Po','Nu','Gi/--Uncontrolled','Gi/--Controlled','Te/--Uncontrolled','Te/--Controlled') for value in item: # remove all digits from port names before filtering result = ''.join(i for i in value.value if not i.isdigit()) if (result in include) or (result not in ignore): ifname = value.value # id defines the interface, will be appended to following snmp get id = value.oid_index #descr = session.get(ifAlias+id) opstatus = ifstatus[session.get(ifOperStatus+'.'+id).value] lastchangedate = lastchange2date(uptime,session.get(ifLastChange+'.'+id).value) print str(ifname)+"\tSTATUS "+opstatus+"\tLAST CHANGE SINCE DAYS\t"+lastchangedate
class SNMP_Service(): def __init__(self, hostname, **kwargs): self.switch = hostname self.version = kwargs.get('version', 2) if self.version < 3: self.community = kwargs.get('community', 'public') self.session = Session(hostname=self.switch, community=self.community, version=self.version) else: self.security_level = kwargs.get('security_level', 'authNoPriv') self.security_username = kwargs.get('security_username', 'opro') self.auth_protocol = kwargs.get('auth_protocol', 'SHA') self.auth_password = kwargs.get('auth_password', '') self.privacy_protocol = kwargs.get('privacy_protocol', 'aes') self.privacy_password = kwargs.get('privacy_password', '') self.session = Session(hostname=self.switch, security_level=self.security_level, security_username=self.security_username, auth_protocol=self.auth_protocol, auth_password=self.auth_password, privacy_protocol=self.privacy_protocol, privacy_password=self.privacy_password, version=self.version) def sys_descr(self): d = self.session.get('sysDescr.0') [descr, fw, rom] = d.value.split(',') return (self.switch, descr, fw, rom) def num_ports(self): d = self.session.get('') [descr, fw, rom] = d.value.split(',') def model(self): d = self.session.get('ENTITY-MIB::entPhysicalModelName.1') return d def firmware(self): d = self.session.get('ENTITY-MIB::entPhysicalSoftwareRev.1') return d def get(self, oid): return self.session.get(oid) def getfirst(self, oid): ret = self.session.get_next(oid) while ret is not None and not len(ret.value): ret = self.session.get_next(ret.oid) return ret def getall(self, oid, filter_by_value=False): ret = self.session.walk(oid) if filter_by_value: return [lambda x: x.value for x in ret] return ret def set(self, oid, value, snmp_type=None): return self.session.set(oid, value, snmp_type) def set_multiple(self, oids): return self.session.set_multiple(oids)
def intstat(ip): ip_stat = {} list1 = [] list2 = [] dict_intf = {'1': 'fa0/0', '2': 'fa1/0', '3': 'fa1/1', '4': 'fa0/1'} dict_status = {'1': 'up', '2': 'down'} sess = Session(hostname=ip, community='public', version=2) sys = sess.walk(oids=u'.1.3.6.1.2.1.2.2.1.8') count = 0 for item in sys: int1 = '{oid}.{oid_index} {snmp_type} = {value}'.format( oid=item.oid, oid_index=item.oid_index, snmp_type=item.snmp_type, value=item.value) add3 = re.split(r'\s', int1) add4 = add3[0].split('.') list1.append(add4[-1]) list2.append(add3[-1]) count += 1 for i in range(0, count): int_name = dict_intf[list1[i]] int_stat = dict_status[list2[i]] ip_stat[int_name] = int_stat return ip_stat
def main(): opts = parseArgs() pyt = pytricia.PyTricia() pyt.insert('0.0.0.0/0', "root") pyt.insert('10.0.0.0/8', "RFC1918 root") pyt.insert('172.12.0.0/12', "RFC1918 root") pyt.insert('192.168.0.0/16', "RFC1918 root") prefx = {} IGNORED_INTERFACE = [ 'bme0' , 'bme0.32768', 'lo' ] for device in opts['hosts']: try: session = Session(hostname=device, community=opts['community'], version=2) ipent = session.walk('IP-MIB::ipAdEntAddr') for item in ipent: ip = item.value ifIndex = session.get('IP-MIB::ipAdEntIfIndex.' + ip) mask = session.get('IP-MIB::ipAdEntNetMask.' + ip) ifName = session.get('IF-MIB::ifName.' + ifIndex.value) if ifName in IGNORED_INTERFACE: print("Skipping %s" % ifName) continue prefix = ip + "/" + str(IPNetwork('0.0.0.0/' + mask.value ).prefixlen) pref = IPNetwork(prefix) pyt.insert(str(prefix), device + "_" + ifName.value) except Exception, err: print("\tTIMEOUT: " +fw) print("\t" + str(err)) continue
def fetchTable(self): session = Session(hostname=SNMP2JSON.args.hostname + ':' + SNMP2JSON.args.port, community=SNMP2JSON.args.community, version=SNMP2JSON.args.version) system_items = session.walk(SNMP2JSON.args.table) data = [] for item in system_items: oid = item.oid oid_index = item.oid_index snmp_type = item.snmp_type value = item.value test = { 'oid': oid, 'oid_index': oid_index, 'snmp_type': snmp_type, 'value': value } data.append(test) allData = { '' + SNMP2JSON.args.table: data } if(SNMP2JSON.args.filename == None): print json.dumps(allData, indent=4, sort_keys=True) else: with open(SNMP2JSON.args.filename, 'wt') as f: f.write(json.dumps(allData, indent=4, sort_keys=True)) print 'JSON Flushed to ' + SNMP2JSON.args.filename
def query_interfaces_status(): interface_dict = {} for id in config.SWITCHES: switch_name = config.SWITCHES[id]["name"] hostname = config.SWITCHES[id]["hostname"] username = config.SWITCHES[id]["username"] password = config.SWITCHES[id]["password"] session = Session(hostname=hostname, security_level=u"auth_with_privacy", security_username=username, auth_protocol=u"SHA", auth_password=password, privacy_password=password, version=3) interfaces_status = session.walk("1.3.6.1.2.1.2.2.1.8") for item in interfaces_status: search_text = "tag:" + switch_name + "_" + parse_interface_name( item.oid.replace("iso.3.6.1.2.1.2.2.1.8.", "")) result_line = "" with open(config.ALLOCATION) as file: for line in file: line = line.rstrip() if search_text in line: result_line = line break if result_line != "": port_ip_address = result_line.split(",")[1] interface_dict[port_ip_address] = item.value return interface_dict
def main(): opts = parseArgs() pyt = pytricia.PyTricia() pyt.insert('0.0.0.0/0', "root") pyt.insert('10.0.0.0/8', "RFC1918 root") pyt.insert('172.12.0.0/12', "RFC1918 root") pyt.insert('192.168.0.0/16', "RFC1918 root") prefx = {} IGNORED_INTERFACE = ['bme0', 'bme0.32768', 'lo'] for device in opts['hosts']: try: session = Session(hostname=device, community=opts['community'], version=2) ipent = session.walk('IP-MIB::ipAdEntAddr') for item in ipent: ip = item.value ifIndex = session.get('IP-MIB::ipAdEntIfIndex.' + ip) mask = session.get('IP-MIB::ipAdEntNetMask.' + ip) ifName = session.get('IF-MIB::ifName.' + ifIndex.value) if ifName in IGNORED_INTERFACE: print("Skipping %s" % ifName) continue prefix = ip + "/" + str( IPNetwork('0.0.0.0/' + mask.value).prefixlen) pref = IPNetwork(prefix) pyt.insert(str(prefix), device + "_" + ifName.value) except Exception, err: print("\tTIMEOUT: " + fw) print("\t" + str(err)) continue
class OpticTransceiver: def __init__(self, node, port): self.node = node self.port = port self.fqdn = node + config['domain'] self.session = self.get_session() self.port_index = self.get_port_index() def get_session(self): self.session = Session(hostname=self.fqdn, community=config['snmp_community'], version=2) return self.session def get_port_index(self): port_number = self.port.split('/')[-1] rx_tag = ' ' + port_number + ' Rx' receive_tag = '/' + port_number + ' Receive' rx_tags = [rx_tag, receive_tag] # walk entity-mib walk = self.session.walk(config['entity_mib']) # filter entity-mib for port index for snmpvar in walk: if any(tag in snmpvar.value for tag in rx_tags): port_oid = snmpvar.oid port_index = port_oid.split('.')[-1] return port_index def poll_light_lvl(self): port_lvl_oid = config['light_lvl_mib'] + self.port_index get = self.session.get(port_lvl_oid) light_lvl = float(get.value) / 10 return(light_lvl) def poll_low_warn_threshold(self): port_threshold_oid = config['light_threshold_mib'] + self.port_index + '.' low_warn_oid = port_threshold_oid + '3' get = self.session.get(low_warn_oid) low_warn = float(get.value) / 10 return(low_warn) def poll_thresholds(self): port_threshold_oid = config['light_threshold_mib'] + self.port_index + '.' high_warn_oid = port_threshold_oid + '1' high_alarm_oid = port_threshold_oid + '2' low_warn_oid = port_threshold_oid + '3' low_alarm_oid = port_threshold_oid + '4' get = self.session.get(low_warn_oid) low_warn = float(get.value) / 10 return(low_warn)
def walk_oids(host, port, oids, community): session = Session(hostname=host, remote_port=port, community=community, version=2, use_numeric=True, use_long_names=True) for oid in oids: system_items = session.walk(oid) for item in system_items: yield item.oid[1:]+"."+item.oid_index, str((item.value).encode('ascii', 'ignore'))
def ospf_func(ip): #Creating empty containers for adding discovered devices nbridlist = [] nbriplist = [] ospf_device = {} #Opening the SNMPv3 session to the device session = Session(hostname=ip, version=3, security_level="auth_with_privacy", security_username="******", auth_protocol="SHA", auth_password="******", privacy_protocol="AES", privacy_password="******") #Getting device OSPF ID snmp_walk = session.walk('.1.3.6.1.2.1.14.1.1') #pprint(snmp_walk) ospf_host_id = snmp_walk[0].value #Performing SNMP WALK to get OSPF neighbor IDs snmp_walk = session.walk('.1.3.6.1.2.1.14.10.1.3') #pprint(snmp_walk) for neighbor_id in snmp_walk: nbridlist.append(neighbor_id.value) #Performing SNMP WALK to get OSPF neighbor IPs snmp_walk = session.walk('.1.3.6.1.2.1.14.10.1.1') #pprint(snmp_walk) for neighbor_ip in snmp_walk: nbriplist.append(neighbor_ip.value) #Building the dictionary with the device's OSPF info ospf_device["HostID"] = ospf_host_id ospf_device["NbrRtrID"] = nbridlist ospf_device["NbrRtrIP"] = nbriplist #pprint(ospf_device) #List of OSPF devices if ospf_device not in ospf: ospf.append(ospf_device) return ospf
def _get_system_name(self, trap_address): self.session_parameters['hostname'] = trap_address session = Session(**self.session_parameters) full_system_name = session.walk('sysName')[0].value return full_system_name
def walk_oids(host, port, oids, community, timeout, retries): session = Session(hostname=host, remote_port=port, community=community, version=2, use_numeric=True, use_long_names=True, timeout=timeout, retries=retries) for oid in oids: system_items = session.walk(oid) for item in system_items: yield item.oid[1:]+"."+item.oid_index, str((item.value).encode('ascii', 'ignore'))
def temp_placas(olt, comnty, pon): """ Retorna a temperatura de cada placa da olt. """ session = Session(hostname=olt, community=comnty, version=2) descs = session.walk('1.3.6.1.4.1.2011.2.6.7.1.1.2.1.10 (hwMusaBoardTemperature)') descs_value = [] for desc in descs: descs_value.append(desc.value) # extrai o valor da descrição return descs_value # retorna uma lista com as descrições
def main(): print('Elige el sensor que quieres usar: ') print('1. Sensor SMTP') print('2. Sensor HTTP') print('3. Sensor FTP') print('4. Sensor CUPS') print('5. Sensor TELNET') opc = int(input('Selecciona tu opcion: ')) if (opc == 1): print('SMTP\n') from_host = "@".join([os.getenv("LOGNAME"), socket.gethostname()]) usuario = input("Escribe el nombre de usuario destino: ") ip = input("Escribe la direccion ip del destino: ") dominio = input("Escribe el dominio: ") puerto = input("Escribe el puerto del dominio: ") sbj = "Comprobando el envío de correo localmente" txt = "Si puedes leer esto, tu servidor local SMTP está OK" send_mail_local(from_host, usuario, ip, dominio, puerto, sbj, txt) #print("Comprueba el correo en tu buzón local") elif (opc == 2): url = input('Introduce la url del sitio web: ') [tiempo, bytes, velocidad] = solicitudHTTP(url) print('Tiempo de respuesta: ', tiempo) print('Bytes descargados: ', bytes) print('Ancho de banda: ' + str(velocidad) + ' bytes por segundo') elif (opc == 3): print('FTP') elif (opc == 4): impresora = input('Introduce la direccion de tu impresora: ') getinfoprinter(impresora) elif (opc == 5): session = Session(hostname='localhost', community="comunidadASR", version=2) print('TELNET') trafico_recibido = session.walk('1.3.6.1.2.1.2.2.1.10') trafico_enviado = session.walk('1.3.6.1.2.1.2.2.1.16') print("Trafico recibido: " + str(trafico_recibido)) print("Trafico enviado: " + str(trafico_enviado)) else: print('No pusiste una opcion valida')
def obtenerSesion(hostname, community, version, tipo, elementoLista): session = Session(hostname=hostname, community=community, version=version) if (tipo == "walk"): description = str(session.walk(elementoLista)) elif (tipo == "get"): description = str(session.get(elementoLista)) else: description = 'Error' return description
def descricao(olt, comnty, pon=None): """ Retorna as descrições das ONUs da PON passada.""" try: # Tentando criar a sessão snmp session = Session(hostname=olt, community=comnty, version=2) except: # algum parâmetro errado print(f"\nAlgum erro ao tentar criar uma sessão, antes mesmo de fazer o snmp walk!\nOLT: {olt}\nCommunity: {comnty}") sys.exit() try: # Tentando realizar o snmpwalk if pon: # pon específica descs_snmp = session.walk(f'.1.3.6.1.4.1.2011.6.128.1.1.2.43.1.9.{pon}') # oid que retorna descrições else: # olt inteira descs_snmp = session.walk('.1.3.6.1.4.1.2011.6.128.1.1.2.43.1.9') # oid que retorna descrições except: # timeout print("Não foi possível realizar o snmp walk das descrições. Aguarde alguns instantes e tente novamente. Saindo...") sys.exit() descs = [] for desc in descs_snmp: descs.append(desc.value) # extrai o valor da descrição return descs # retorna uma lista com as descrições
def serial(olt, comnty, pon=None): """ Retorna o serial de cada onu na pon passada. """ # falta validar try: # Tentando criar a sessão snmp session = Session(hostname=olt, community=comnty, version=2) except: # algum parâmetro errado print(f"\nAlgum erro ao tentar criar uma sessão, antes mesmo de fazer o snmp walk!\nOLT: {olt}\nCommunity: {comnty}") sys.exit() try: # Tentando realizar o snmpwalk if pon: # pon específica seriais_snmp = session.walk(f'.1.3.6.1.4.1.2011.6.128.1.1.2.43.1.3.{pon}') # oid que retorna descrições else: # olt inteira seriais_snmp = session.walk('.1.3.6.1.4.1.2011.6.128.1.1.2.43.1.3') # oid que retorna descrições except: # timeout print("Não foi possível realizar o snmp walk dos seriais. Aguarde alguns instantes e tente novamente. Saindo...") sys.exit() seriais = [] for serial in seriais_snmp: seriais.append(serial.value) # extrai o valor da descrição return seriais # retorna uma lista com as descrições
def cdpplat(h, c): i = 0 session = Session(hostname=h, community=c, version=2) cplat = session.walk('1.3.6.1.4.1.9.9.23.1.2.1.1.8') while i < len(cplat): s_plat = cplat[i].value i = i + 1 newplat.append(s_plat) return
def cdpname(h, c): i = 0 session = Session(hostname=h, community=c, version=2) cname = session.walk('1.3.6.1.4.1.9.9.23.1.2.1.1.6') while i < len(cname): s_name = cname[i].value i = i + 1 newname.append(s_name) return
def getInterfaces(ipRouter, rname=None): global network session = Session(hostname=ipRouter, community=COMMUNITY, version=2) router = network.getRouter(rname) ipslist = (session.walk('RFC1213-MIB::ipAdEntAddr')) for ip in ipslist: index = (session.get('RFC1213-MIB::ipAdEntIfIndex.' + ip.value)) name = (session.get('IF-MIB::ifDescr.' + index.value)) mask = (session.get('RFC1213-MIB::ipAdEntNetMask.' + ip.value)) speed = (session.get('IF-MIB::ifSpeed.' + index.value)) cost = (session.get('OSPF-MIB::ospfIfMetricValue.' + ip.value))
def snmp_work(job): """ Do SNMP-work """ session = Session( hostname=job['hostname'], community=job['community'], version=2, retries=1, timeout=5, ) return session.walk(job['oids'])
def uptime_olt(olt, comnty): """ Uptime da OLT em ticks. Conversões: segundos = ticks / 100 minutos = ticks / 6,000 horas = ticks / 360,000 dias = ticks / 8,640,000 Por padrão, retorno em dias. """ session = Session(hostname=olt, community=comnty, version=2) uptime_ticks = session.walk('1.3.6.1.2.1.1.3') # Uptime da OLT em ticks return int(int(uptime_ticks[0].value) / 60 / 60 /24 / 100) # Dias
def last_downtime(olt, comnty, pon=None): """ Retorna data + hora da última queda de cada onu da pon passada. """ try: # Tentando criar a sessão snmp session = Session(hostname=olt, community=comnty, version=2, use_sprint_value=False) except: # algum parâmetro errado print(f"\nAlgum erro ao tentar criar uma sessão, antes mesmo de fazer o snmp walk!\nOLT: {olt}\nCommunity: {comnty}") sys.exit() try: # Tentando realizar o snmpwalk if pon: # pon específica last_downtime = session.walk(f'.1.3.6.1.4.1.2011.6.128.1.1.2.46.1.23.{pon}') # oid que retorna o Downtime (em hexadecimal) else: # olt inteira last_downtime = session.walk('.1.3.6.1.4.1.2011.6.128.1.1.2.46.1.23') # oid que retorna o Downtime (em hexadecimal) except: # timeout print("Não foi possível realizar o snmp walk do último downtime. Aguarde alguns instantes e tente novamente. Saindo...") sys.exit() last_downtime_formatado = [] for data_bin in last_downtime: data_hex = bin_to_hex(data_bin.value) onu_dt_lst = data_hex.split() ano, mes, dia, hora, minuto, segundo = onu_dt_lst[0], onu_dt_lst[1], onu_dt_lst[2], onu_dt_lst[3], onu_dt_lst[4], onu_dt_lst[5] last_downtime_formatado.append(f'{int(dia, 16):02d}-{int(mes, 16):02d}-{int(ano, 16)} {int(hora, 16):02d}:{int(minuto, 16):02d}:{int(segundo, 16):02d}') return last_downtime_formatado
def get_lldp_a3_cisco(a3_arg, element_arg): #Первый A3 session_a3_1 = Session(hostname=a3_arg, community='ntcore', version=2) oid_lldp = session_a3_1.walk('.1.0.8802.1.1.2.1.4.1.1.9') for item in oid_lldp: if element_arg in str(item.value): #print "FIND" #print '{oid}.{oid_index} {snmp_type} = {value}'.format( #oid=item.oid, #oid_index=item.oid_index, #snmp_type=item.snmp_type, #value=item.value #) tmp_parse = [] for q in str(item.oid).split('.'): tmp_parse.append(q) ports_1.append(str(tmp_parse[12])) print (a3_arg) print("Элемент " + element_arg + " найден на порту: " + str(ports_1)) print ("Магистральные порты: " + cfg_ini['Agg_links_cisco']['cisco_po1'] + ", " +cfg_ini['Agg_links_cisco']['cisco_po2']) print ('--------------------------------------------------------') #Второй A3 session_a3_2 = Session(hostname=cfg_ini['A3'][a3_arg], community='ntcore', version=2) oid_lldp = session_a3_2.walk('.1.0.8802.1.1.2.1.4.1.1.9') for item in oid_lldp: if element_arg in str(item.value): tmp_parse = [] for q in str(item.oid).split('.'): tmp_parse.append(q) ports_2.append(str(tmp_parse[12])) print (cfg_ini['A3'][a3_arg]) print("Элемент " + element_arg + " найден на порту: " + str(ports_2)) print ("Магистральные порты: " + cfg_ini['Agg_links_cisco']['cisco_po1'] + ", " + cfg_ini['Agg_links_cisco']['cisco_po2']) print ('--------------------------------------------------------\n') return (ports_1, ports_2)
class SnmpWalker: def __init__(self, host, community, version): self.host = host self.community = community self.version = version self.create_session() def create_session(self): self.session = Session(hostname=self.host, community=self.community, version=self.version) def walk_through(self, oid): return self.session.walk(oid)
class SNMPBaseWorker(object, metaclass=ABCMeta): ses = None def __init__(self, ip: Optional[str], community='public', ver=2): if ip is None or ip == '': raise DeviceImplementationError(gettext('Ip address is required')) self._ip = ip self._community = community self._ver = ver def start_ses(self): if self.ses is None: self.ses = Session( hostname=self._ip, community=self._community, version=self._ver ) def set_int_value(self, oid: str, value): self.start_ses() return self.ses.set(oid, value, 'i') def get_list(self, oid) -> Generator: self.start_ses() for v in self.ses.walk(oid): yield v.value def get_list_keyval(self, oid) -> Generator: self.start_ses() for v in self.ses.walk(oid): snmpnum = v.oid.split('.')[-1:] yield v.value, snmpnum[0] if len(snmpnum) > 0 else None def get_item(self, oid): self.start_ses() v = self.ses.get(oid).value if v != 'NOSUCHINSTANCE': return v
def main(): parser = argparse.ArgumentParser() parser.add_argument("-H", "--hostname", help="IP Address / Hostname to check [REQUIRED]",type=str, required=True) parser.add_argument("-c", "--community",help="SNMP Community (default 'public')",type=str,default='public') parser.add_argument("-d", "--down",help="Show only down interfaces (default n)",type=str,choices=['y', 'n'],default='n') # port names to include or ignore to filter useless values include= ('ethernet') ignore = ('StackSub-St-','StackPort','Vl','vlan','VLAN','VLAN-','Trk','lo','oobm','Po','Nu','Gi/--Uncontrolled','Gi/--Controlled','Te/--Uncontrolled','Te/--Controlled') args = parser.parse_args() hostname = args.hostname session = Session(hostname=hostname, community=args.community, version=2) try: item = session.walk(ifName) except: sys.exit('\nSNMP CONNECTION PROBLEM host '+hostname+" check IP and COMMUNITY\n") # get uptime to calculate last change uptime = session.get(sysUpTime).value print('\nHOST\t {}'.format(hostname)) print("\nDEVICE UPTIME\t {}\n".format(str(timedelta(seconds=(int(uptime)/100))))) for value in item: # remove all digits from port names before filtering result = ''.join(i for i in value.value if not i.isdigit()) if (result in include) or (result not in ignore): ifname = value.value # id defines the interface, will be appended to following snmp get id = value.oid_index if not id: id = value.oid.split(".")[-1] opstatus = ifstatus[session.get(ifOperStatus+'.'+id).value] lastchangedate = lastchange2date(uptime,session.get(ifLastChange+'.'+id).value) if args.down == 'n': x.add_row([ifname,opstatus,lastchangedate]) else: if opstatus == 'down': x.add_row([ifname,opstatus,lastchangedate]) print(x.get_string())
queryDict[devClass] = [] for oid in oList: oidName = oid['name'] oidNum = oid['oid'] queryDict[devClass].append(oidNum) for device in devices['devices']: ipAddr = device['ip'] name = device['name'] devClass = device['type'] community = device['rocomm'] try: session = Session(hostname=ipAddr, community=community, version=2, timeout=snmpTimeout, retries=0) #print "Device %s (%s) will poll oids %s" % (name, ipAddr, queryDict[devClass]) for o in queryDict[devClass]: x= session.walk(o) for val in x: #print "%s: %s" % (val.oid_index, val.value) pass except easysnmp.EasySNMPTimeoutError, e: print "Device %s (%s) timed out when requesting oid %s" % (name, ipAddr, o) except easysnmp.EasySNMPError, e: print "Non-timeout error from %s (%s) for oid %s" % (name, ipAddr, o) #print "OIDs:" #pprint.pprint(queryDict) end = time.time() print "Elapsed time was %d seconds" % (end - start)
class CiscoIpSlaChecker: STATUS_OK = 0 STATUS_WARNING = 1 STATUS_CRITICAL = 2 STATUS_UNKNOWN = 3 # Verbosity levels V_NONE = 0 V_INFO = 1 V_DEBUG = 2 def __init__(self): self.status = None self.message = None self.perfdata = None self.session = None self.options = None self.rtt_dict = dict() def run(self): self.parse_options() try: self.create_snmp_session() self.read_rtt_entries() except EasySNMPError as e: self.add_status(self.STATUS_UNKNOWN) self.message = "SNMP error checking {}, {}".format(self.options.hostname, e) else: if "list" == self.options.mode: self.list_rtt() elif "check" == self.options.mode: self.check() self.print_output() return self.status def parse_options(self): parser = argparse.ArgumentParser( description="Monitoring check plugin to check Cisco SLA status for one or more entries" ) parser.add_argument("-H", "--hostname", help="Hostname or ip-address") parser.add_argument("-v", "--version", default="2", choices=["1", "2", "3"], help="SNMP version (default '2')") parser.add_argument("-c", "--community", default="public", help="SNMP Community (default 'public')") parser.add_argument("-u", "--security-name", help="SNMP v3 security name (username)") parser.add_argument("-l", "--security-level", default="authPriv", choices=["noAuthNoPriv", "authNoPriv", "authPriv"], help="SNMP v3 security level (default 'authPriv')") parser.add_argument("-p", "--password", help="SNMP v3 password (used for both authentication and privacy)") parser.add_argument("-a", "--auth-protocol", default="SHA", choices=["MD5", "SHA"], help="SNMP v3 authentication protocol (default 'SHA')") parser.add_argument("-A", "--auth-password", help="SNMP v3 authentication password, overrides --password if set") parser.add_argument("-x", "--priv-protocol", default="AES", choices=["DES", "AES"], help="SNMP v3 privacy protocol (default 'AES')") parser.add_argument("-X", "--priv-password", help="SNMP v3 privacy password, overrides --password if set") parser.add_argument("-m", "--mode", choices=["list", "check"], help="Operation mode") parser.add_argument("-e", "--entries", default="all", help="SLA entry (or entries) to check, specify as 'all', " "a single value or comma-separated list") parser.add_argument("--perf", action="store_true", help="Return perfdata") parser.add_argument("--critical-pct", default=None, type=float, help="Critical threshold in percentage of failed SLAs (default '100')") parser.add_argument("--warning-pct", default=None, type=float, help="Warning threshold in percentage of failed SLAs (default '50')") parser.add_argument("--critical", default=None, type=int, help="Critical threshold in amount of failed SLAs") parser.add_argument("--warning", default=None, type=int, help="Warning threshold in amount of failed SLAs") parser.add_argument("--verbose", default=0, type=int, choices=[0, 1, 2], help="Verbose output") self.options = parser.parse_args() # Set default warning and critical levels if they are not specified at all if self.options.critical is None and self.options.critical_pct is None: self.options.critical_pct = 100 if self.options.warning is None and self.options.warning_pct is None: self.options.warning_pct = 50 # Copy password to auth-password and priv-password if applicable if self.options.auth_password is None and self.options.password is not None: self.options.auth_password = self.options.password if self.options.priv_password is None and self.options.password is not None: self.options.priv_password = self.options.password if not self.are_options_valid(): print("Run with --help for usage information") print("") exit(0) self.print_msg(self.V_DEBUG, "Using parameters:") self.print_msg(self.V_DEBUG, " Hostname: {}".format(self.options.hostname)) self.print_msg(self.V_DEBUG, " SNMP-version: {}".format(self.options.version)) self.print_msg(self.V_DEBUG, " Community: {}".format(self.options.community)) self.print_msg(self.V_DEBUG, " Security-name: {}".format(self.options.security_name)) self.print_msg(self.V_DEBUG, " Security-level: {}".format(self.options.security_level)) self.print_msg(self.V_DEBUG, " Password: {}".format(self.options.password)) self.print_msg(self.V_DEBUG, " Auth-protocol: {}".format(self.options.auth_protocol)) self.print_msg(self.V_DEBUG, " Auth-password: {}".format(self.options.auth_password)) self.print_msg(self.V_DEBUG, " Priv-protocol: {}".format(self.options.priv_protocol)) self.print_msg(self.V_DEBUG, " Priv-password: {}".format(self.options.priv_password)) self.print_msg(self.V_DEBUG, " Mode: {}".format(self.options.mode)) self.print_msg(self.V_DEBUG, " SLA entries: {}".format(self.options.entries)) self.print_msg(self.V_DEBUG, " Perf-data: {}".format(self.options.perf)) self.print_msg(self.V_DEBUG, " Critical-pct: {}".format(self.options.critical_pct)) self.print_msg(self.V_DEBUG, " Warning-pct: {}".format(self.options.warning_pct)) self.print_msg(self.V_DEBUG, " Critical: {}".format(self.options.critical)) self.print_msg(self.V_DEBUG, " Warning: {}".format(self.options.warning)) self.print_msg(self.V_DEBUG, " Verbosity: {}".format(self.options.verbose)) self.print_msg(self.V_DEBUG, "") def are_options_valid(self): if not self.options.hostname: print("You must specify a hostname") return False if not self.options.mode: print("You must specify a operation mode") return False if self.options.mode == "check" and not self.options.entries: print("You must specify SLA-entries for check-mode (use list-mode to list existing entries)") return False return True def print_msg(self, minimum_verbosity_level, msg): """ :param minimum_verbosity_level: Minimum verbosity level needed for the message to be printed :param msg: The message to print :return: """ if self.options.verbose >= minimum_verbosity_level: print(msg) def print_output(self): """ Prints the final output (in Nagios plugin format if self.status is set) :return: """ output = "" if self.status == self.STATUS_OK: output = "OK" elif self.status == self.STATUS_WARNING: output = "Warning" elif self.status == self.STATUS_CRITICAL: output = "Critical" elif self.status == self.STATUS_UNKNOWN: output = "Unknown" if self.message: if len(output): output += " - " output += self.message if self.perfdata: if len(output): output += " | " output += self.perfdata print(output) def create_snmp_session(self): self.session = Session( hostname=self.options.hostname, community=self.options.community, version=int(self.options.version), security_username=self.options.security_name, security_level=self.options.security_level, auth_protocol=self.options.auth_protocol, auth_password=self.options.auth_password, privacy_protocol=self.options.priv_protocol, privacy_password=self.options.priv_password, ) def add_status(self, status): """ Set the status only if it is more severe than the present status The order of severity being OK, WARNING, CRITICAL, UNKNOWN :param status: Status to set, one of the self.STATUS_xxx constants :return: The current status """ if self.status is None or status > self.status: self.status = status def read_rtt_entries(self): # Get SLA entry info self.rtt_dict = dict() rtt_ctrl_admin_entries = self.session.walk(".1.3.6.1.4.1.9.9.42.1.2.1.1") for item in rtt_ctrl_admin_entries: oid_parts = str(item.oid).split(".") rtt_entry = oid_parts[-1] rtt_info_type = oid_parts[-2] if rtt_entry not in self.rtt_dict: self.rtt_dict[rtt_entry] = dict() if "2" == rtt_info_type: # rttMonCtrlAdminOwner (2) self.rtt_dict[rtt_entry]["owner"] = str(item.value) elif "3" == rtt_info_type: # rttMonCtrlAdminTag (3) self.rtt_dict[rtt_entry]["tag"] = str(item.value) elif "4" == rtt_info_type: # rttMonCtrlAdminRttType (3) self.rtt_dict[rtt_entry]["type"] = str(item.value) # Get SLA entry status rtt_ctrl_oper_entries = self.session.walk(".1.3.6.1.4.1.9.9.42.1.2.9.1") for item in rtt_ctrl_oper_entries: oid_parts = str(item.oid).split(".") rtt_entry = oid_parts[-1] rtt_info_type = oid_parts[-2] if "5" == rtt_info_type: # rttMonCtrlOperConnectionLostOccurred (5) if item.value == "1": self.rtt_dict[rtt_entry]["conn_lost_occured"] = True else: self.rtt_dict[rtt_entry]["conn_lost_occured"] = False elif "6" == rtt_info_type: # rttMonCtrlOperTimeoutOccurred (6) if item.value == "1": self.rtt_dict[rtt_entry]["timeout_occured"] = True else: self.rtt_dict[rtt_entry]["timeout_occured"] = False elif "7" == rtt_info_type: # rttMonCtrlOperOverThresholdOccurred (7) if item.value == "1": self.rtt_dict[rtt_entry]["over_thres_occured"] = True else: self.rtt_dict[rtt_entry]["over_thres_occured"] = False elif "10" == rtt_info_type: # rttMonCtrlOperState (10) # http://tools.cisco.com/Support/SNMP/do/BrowseOID.do?local=en&translate=Translate&objectInput=1.3.6.1.4.1.9.9.42.1.2.9.1.10 if item.value == "6": self.rtt_dict[rtt_entry]["in_active_state"] = True else: self.rtt_dict[rtt_entry]["in_active_state"] = False def list_rtt(self): """ Reads the list of available SLA entries for the device and prints out a list :return: """ sla_list = list() inactive_sla_list = list() for rtt_entry in self.rtt_dict: rtt_id = "{0}".format(rtt_entry) if self.rtt_dict[rtt_entry]["tag"]: rtt_id += " (tag: {0})".format(self.rtt_dict[rtt_entry]["tag"]) if self.rtt_dict[rtt_entry]["in_active_state"]: sla_list.append(" {0}".format(rtt_id)) else: inactive_sla_list.append(" {0} (inactive)".format(rtt_id)) sla_list.extend(inactive_sla_list) if len(sla_list) == 0: self.message = "No SLAs available" else: self.message = "SLAs available:\n" for sla in sla_list: self.message += sla + "\n" def check(self): messages = [] if self.options.entries == "all": requested_entries = self.rtt_dict.keys() else: requested_entries = self.options.entries.replace(" ", "").split(",") # Initialize status to OK (if status is not set yet) self.add_status(self.STATUS_OK) ok_count = 0 failed_count = 0 for requested_entry in requested_entries: if requested_entry not in self.rtt_dict: self.message = "SLA {0} does not exist".format(requested_entry) self.add_status(self.STATUS_UNKNOWN) return else: rtt_id = "{0}".format(requested_entry) if self.rtt_dict[requested_entry]["tag"]: rtt_id += " (tag: {0})".format(self.rtt_dict[requested_entry]["tag"]) if self.rtt_dict[requested_entry]["in_active_state"]: if self.rtt_dict[requested_entry]["timeout_occured"]: failed_count += 1 messages.append("Timeout for SLA {0}".format(rtt_id)) else: ok_count += 1 else: messages.append("SLA {0} not active".format(rtt_id)) self.add_status(self.STATUS_WARNING) if failed_count + ok_count == 0: messages.append("No SLAs checked") self.add_status(self.STATUS_UNKNOWN) return failed_pct = round(float(failed_count) / (failed_count + ok_count) * 100, 1) # Check percentage thresholds (if set) if self.options.critical_pct is not None and failed_pct >= self.options.critical_pct: self.add_status(self.STATUS_CRITICAL) if self.options.warning_pct is not None and failed_pct >= self.options.warning_pct: self.add_status(self.STATUS_WARNING) # Check absolute thresholds (if set) if self.options.critical is not None and failed_count >= self.options.critical: self.add_status(self.STATUS_CRITICAL) if self.options.warning is not None and failed_count >= self.options.warning: self.add_status(self.STATUS_WARNING) if failed_count: # Don't show percentage-failed when only checking one SLA if failed_count + ok_count == 1: messages.insert(0, "{0} Failed".format(failed_count)) else: messages.insert(0, "{0} Failed ({1}%)".format(failed_count, failed_pct)) if ok_count: messages.insert(0, "{0} OK".format(ok_count)) if messages: self.message = ", ".join(messages) if self.options.perf: self.perfdata = "'Failed%'={0}%".format(failed_pct) if self.options.critical_pct and self.options.warning_pct: self.perfdata += ";{0};{1};0;100".format(self.options.warning_pct, self.options.critical_pct)
class Router(Host): def __init__(self, ip, community): # Do the normal things for any network object. self.hostinit(ip) # Initiate SNMP self.session = Session(hostname=str(self.ip), community=community, version=1) @property def routes(self): return self.__routes @routes.setter def routes(self, data): print('route set on', self.ip) self.__routes = data def walk(self, mib): # Walks the specified mib try: responses = self.session.walk(mib) return responses except easysnmp.exceptions.EasySNMPNoSuchNameError: # Probably means that you're hitting the wrong kind of device print('nosuchname') return False except easysnmp.exceptions.EasySNMPTimeoutError: # Either the community string is wrong, or you're pinging dead space print('timeout') return False def getArpTable(self): # A walk of the ARP table, gives list of dicts print('Scanning ARP table for router at:', self.ip) # MIB for ARP tables mib = 'ipNetToMediaPhysAddress' responses = self.walk(mib) arpTable = [] self.arpByMac = {} self.arpByIp = {} # Conditional, so that we don't error on empty responses if responses: ignored = 0 errors = 0 for response in responses: try: # Validation occurs in the decoding, just move on if they # throw assertion errors. mac = Mac(response.value, encoding='utf-16') ip = Ip(response.oid_index, encoding='snmp') #print('MAC: ' + str(mac) + ' IP: ' + str(ip)) values = {} values['mac'] = str(mac) values['ip'] = str(ip) # We also want to know where the ARP record came from. values['source'] = str(self.ip) # We ignore data points that have to do with locally # administered MAC addresses. localMacs = ['2', '6', 'a', 'e'] if values['mac'][1] in localMacs: ignored += 1 else: arpTable.append(values) self.arpByMac[mac] = ip self.arpByIp[ip] = mac except AssertionError: # Malformed input is to be ignored. errors += 1 pass print('Recorded', len(arpTable), 'ARP values with', errors, 'errors, ignoring', ignored, 'virtual MAC addresses.') return arpTable def getRoutingTable(self): print('Scanning routing table for router at:', self.ip) # Walk the routing table mib = 'ipCidrRouteTable' responses = self.walk(mib) errors = 0 routes = {} # Internally, we'll want to do lookups, so dict. print('Recieved', len(responses), 'SNMP responses from', self.ip) for r in responses: try: # An assumption is that the destinations come first. if r.oid == 'ipCidrRouteDest': # Introduce the route. routes[r.oid_index] = {'destination':Ip(r.value), 'router':self.ip} # The other conditions just add values. elif r.oid == 'ipCidrRouteMask': routes[r.oid_index]['netmask'] = Netmask(r.value) elif r.oid == 'ipCidrRouteNextHop': routes[r.oid_index]['nexthop'] = Ip(r.value) except KeyError: # Would mean that a value came in without our seeing the # destination first. errors += 1 # The index on this is useless outside of populating the routes. # I'm going to do a single pass to make a more useful index. self.routes = {} for r in routes.values(): self.routes[r['destination']+str(r['netmask'])+r['nexthop']] = r print('Parsed', len(self.routes), 'routes.') return self.routes
from easysnmp import Session import sys olt_ip = sys.argv[1] olt_port = sys.argv[2] #Alarm only PON ports that has more than this value (variable [alarm] value) alarm = 2 snmpSession = Session(hostname=olt_ip, community='adsl', version=2) mib_status = "1.3.6.1.4.1.5875.800.3.9.3.4.1.5" mib_onu_pon_num = "1.3.6.1.4.1.5875.800.3.9.3.4.1.12" pon_name_list = snmpSession.walk('1.3.6.1.4.1.5875.800.3.9.3.4.1.2') indice = [] for j in range(1,17): for i, elem in enumerate(pon_name_list): if olt_port+"/"+str(j)+"\'" == str(elem).split()[2]: indice.append(i) key = 0 result = {} for i in indice: key = key+1 mib_port = str(pon_name_list[i]).split()[3][41:][:-2] readport = snmpSession.get(mib_status+"."+mib_port) ponNumOnu = snmpSession.get(mib_onu_pon_num+"."+mib_port)