def init_bgp_pe(self): self.list_bgp_pe["10.235.252.15"] = CiscoXR("10.235.252.15", "NAP_1_9K", self.master) self.list_bgp_pe["10.235.252.18"] = CiscoXR("10.235.252.18", "NAP_2_9K", self.master) self.list_bgp_pe["10.250.55.225"] = CiscoXR("10.250.55.225", "GT_GUY_9K", self.master) self.list_bgp_pe["10.234.5.194"] = CiscoXR("10.234.5.194", "CR_SPE_9K", self.master) self.list_bgp_pe["10.234.5.171"] = CiscoXR("10.234.5.171", "CR_ESC_9k", self.master) self.list_bgp_pe["10.244.1.12"] = CiscoIOS("10.244.1.12", "HN_TEG_1000", self.master) self.list_bgp_pe["10.243.1.8"] = CiscoIOS("10.243.1.8", "SV_SMA_1000", self.master) self.list_bgp_pe["192.168.205.55"] = CiscoIOS("192.168.205.55", "PN_PTY_1000", self.master) self.list_bgp_pe["192.168.205.55"].set_jump_gateway( "10.250.55.3", "telnet") self.list_bgp_pe["192.168.250.33"] = CiscoIOS("192.168.250.33", "NI_PTY_1000", self.master) self.list_bgp_pe["192.168.250.33"].set_jump_gateway( "10.250.55.3", "telnet")
def devices_from_network(self, string_network, window=30): network = ipaddress.ip_network(string_network) hosts = network.hosts() host_string_ip = [] for host in hosts: host_string_ip.append(str(host)) final_responses = {} final_no_responses = {} ip_devices = [] while (len(host_string_ip) > 0): if (window > (len(host_string_ip))): window = len(host_string_ip) responses, no_responses = multi_ping(host_string_ip[0:window - 1], timeout=1, retry=2) # pprint(responses) if (window == len(host_string_ip)): host_string_ip = [] else: host_string_ip = host_string_ip[window:] # pprint(host_string_ip) ip_devices = ip_devices + [*responses] self.verbose.info("responses {0}".format(len(str( responses.keys())))) final_responses = {**responses, **final_responses} devices = [] self.logger_connection.info("Devices up {0} in net {1}".format( len(ip_devices), string_network)) for ip in ip_devices: device = CiscoIOS(ip, "ios", self.master) devices.append(device) self.verbose.debug("Devices created {0}".format(len(devices))) devices = self.correct_device_platform(devices) self.verbose.debug("devices corrected {0}".format(len(devices))) return devices, ip_devices
def recollect_ospf_topology(self, initial_device_rid="172.16.30.3", shelve_name="prueba"): thread_count = 10 topology = shelve.open(shelve_name) dict_ospf_neigbors = {} initial_devices = [ CiscoIOS(ip=initial_device_rid, display_name="initial_device", master=self.master) ] global_not_conected = [] working_devices = self.correct_device_platform(initial_devices) new_working_devices = [] while len(working_devices) > 0: threads = [] while len(threads) < thread_count and len(working_devices) > 0: device = working_devices.pop() if (device.ip not in dict_ospf_neigbors): t = th.Thread(target=device.set_ospf_topology, kwargs={ "new_working_devices": new_working_devices, "dict_ospf_neigbors": dict_ospf_neigbors }) t.start() threads.append(t) for t in threads: t.join() new_working_devices, not_connected = self.clean_list_devices( new_working_devices) working_devices = self.correct_device_platform(new_working_devices) global_not_conected.append(not_connected)
def __init__(self, network_model, device_ip, prefix, vrf="null", parent="null"): self.state = "init" self.network_model = network_model self.device_ip = device_ip self.device = CiscoIOS(self.device_ip, self.device_ip, self.network_model.master) self.prefix = prefix self.ip_route = "null" self.vrf = vrf self.parent_path = parent self.next_hops = {} self.incoming_interfaces = []
def get_device_list(self, filename): device_list = self.read_file(filename=filename) devices = [] for row in device_list: row = row.replace("\n", "").split(";") device = CiscoIOS(row[0], "ios", self.master) devices.append(device) return devices
def __init__(self, master, ip_list=[], network="", platfforms={}, check_up=True): self.errors = {} self.master = master self.devices = dict() self.uid_devices = {} if network != "" and len(ip_list) == 0: ip_list = [ str(host) for host in ipaddress.ip_network(network).hosts() ] for ip in ip_list: if not platfforms: self.devices[ip] = CiscoIOS(ip=ip, display_name="", master=master) else: self.devices[ip] = eval(platfforms[ip])(ip=ip, display_name="", master=master) if check_up: self.execute(methods=["check_able_connect"], thread_window=50) self._not_connected_devices = { ip: device for ip, device in self.devices.items() if not device.able_connect } self.devices = { ip: device for ip, device in self.devices.items() if device.able_connect } self.execute(methods=["set_snmp_community"], thread_window=50) if not platfforms: self.__correct_classes() self.set_uid = False
def parse_route_ios(input_show): ip_route = IpRoute() has_vrf = (input_show.find("Routing Table:") > -1) # print("has vrf" + str(has_vrf)) lines = input_show.split("\n") lines.reverse() # print(lines) if has_vrf: # print(lines) # print("made pop vrf") lines.pop() ip_route.vrf = lines.pop().replace("Routing Table: ", "") # print(lines) # print("made pop route") # print(lines) route_line = lines.pop().replace("Routing entry for ", "").replace(", supernet", "") # print(route_line) ip_route.prefix = ipaddress.ip_network(route_line) # print("made pop protocol") split_protocol_line = lines.pop().split(",") known_via_split = split_protocol_line[0].replace( " Known via \"", "").replace("\"", "").split(" ") ip_route.protocol = known_via_split[0] if (len(known_via_split) > 1): ip_route.protocol_as = known_via_split[1] ip_route.admin_distance = split_protocol_line[1].replace( " distance ", "replace") ip_route.protocol_metric = split_protocol_line[2].replace( " metric ", "").split(" ")[0] if len(split_protocol_line) > 3: ip_route.protocol_type = split_protocol_line[3] split_paths = input_show.split( " Routing Descriptor Blocks:\n")[1].split("\n") paths = [] for index, line in enumerate(split_paths): if (line.find("from") > -1): path = { "next_hop": "0.0.0.0", "originator": "0.0.0.0", "time": "0", "out_interface": "recursive" } route_info = line.split(",") path["next_hop"] = route_info[0].replace(" ", "").replace("*", "") path["originator"] = route_info[1].replace(" ", "").replace( "from", "") path["time"] = route_info[2].replace(" ", "").replace("ago", "") if (len(route_info) > 3): path[ "out_interface"] = CiscoIOS.get_normalize_interface_name( route_info[3].replace(" ", "").replace("via", "")) if (path["next_hop"].find("(default)") > -1): path["out_interface"] = "recusive_default" path["next_hop"] = path["next_hop"].replace( "(default)", "") # print(route_info) paths.append(path) ip_route.paths = paths return ip_route
def parse_route_xr(input_show, vrf="null"): '''RP/0/RP0/CPU0:GNCYGTG2N2D4B07A02FWT1#show route 10.1.5.64 Mon Feb 26 13:43:17.769 GMT Routing entry for 10.1.5.64/30 Known via "ospf 14754", distance 110, metric 20, type extern 2 Installed Feb 26 11:27:48.070 for 02:15:29 Routing Descriptor Blocks 10.192.16.153, from 10.192.129.114, via HundredGigE0/1/0/0 Route metric is 20 10.192.47.46, from 10.192.129.114, via HundredGigE0/5/0/0 Route metric is 20 No advertising protos. RP/0/RSP0/CPU0:HHERCRMPN1T1FFM4#show route vrf CR_TELEPRESENCE 10.1.63.112 Mon Feb 26 13:44:48.382 GMT Routing entry for 10.1.63.112/29 Known via "bgp 14754", distance 200, metric 0, type internal Installed Feb 23 02:17:20.264 for 3d11h Routing Descriptor Blocks 10.192.129.19, from 10.192.9.30 Nexthop in Vrf: "default", Table: "default", IPv4 Unicast, Table Id: 0xe0000000 Route metric is 0 No advertising protos. ''' ip_route = IpRoute() lines = input_show.split("\n") lines.reverse() lines.pop() lines.pop() route_line = lines.pop().replace("Routing entry for ", "").replace(", supernet", "") ip_route.prefix = ipaddress.ip_network(route_line) split_protocol_line = lines.pop().split(",") known_via_split = split_protocol_line[0].replace( " Known via \"", "").replace("\"", "").split(" ") ip_route.protocol = known_via_split[0] if (len(known_via_split) > 1): ip_route.protocol_as = known_via_split[1] ip_route.admin_distance = split_protocol_line[1].replace( " distance ", "replace") ip_route.protocol_metric = split_protocol_line[2].replace( " metric ", "").split(" ")[0] if len(split_protocol_line) > 3: ip_route.protocol_type = split_protocol_line[3] split_paths = input_show.split( " Routing Descriptor Blocks\n")[1].split("\n") paths = [] for index, line in enumerate(split_paths): if (line.find("from") > -1): path = { "next_hop": "0.0.0.0", "originator": "0.0.0.0", "time": "0", "out_interface": "recursive" } route_info = line.split(",") path["next_hop"] = route_info[0].replace(" ", "").replace("*", "") path["originator"] = route_info[1].replace(" ", "").replace( "from", "") path["time"] = "xr" if (len(route_info) > 2): path[ "out_interface"] = CiscoIOS.get_normalize_interface_name( route_info[2].replace(" ", "").replace("via", "")) if (path["next_hop"].find("(default)") > -1): path["out_interface"] = "recusive_default" path["next_hop"] = path["next_hop"].replace( "(default)", "") paths.append(path) ip_route.paths = paths return ip_route
import ipaddress from model.BGPNeigbor import BGPNeighbor import time from model.InterfaceUfinet import InterfaceUfinet from model.Devices import Devices from model.ospf_database import ospf_database import datetime from tools import PerformanceLog from threading import Thread from pprint import pprint isp = ISP() isp.master = Master() isp.master.username = '******' isp.master.password = '******' device = CiscoIOS(ip='172.16.30.5', display_name='a', master=isp.master, ) period_start = '2019-07-10 00:00:00' base = datetime.datetime.strptime(period_start, '%Y-%m-%d %H:%M:%S') x = 1 date_list = [str(base + datetime.timedelta(hours=x)) for x in range(0, 25)] print(date_list) regional = { "ip_seed_router": "172.16.30.5", "process_id": '1', "area": '0', 'network_name': '_ospf_ufinet_regional' } guatemala = { "ip_seed_router": "172.17.22.52", "process_id": '502', "area": '502008', 'network_name': 'RCE_GUATEMALA' }
def tabulate_mpls_traffic_tunnels(self, ip_lsr_router, filename="test_mpls"): lsr = CiscoIOS(master=self.master, ip=ip_lsr_router, display_name="lsr") lsr.set_mpls_te_tunnels() pprint(len(lsr.mpls_te_tunnels)) mpls_te_data = lsr.mpls_te_tunnels cisco_sources = {} threads = [] device_list = [] result = [] for tunnel_instance, tunnel in mpls_te_data.items(): if (tunnel["source_ip"] not in cisco_sources): cisco_sources[tunnel["source_ip"]] = CiscoIOS( master=self.master, ip=tunnel["source_ip"], display_name=tunnel["source_ip"]) methods = { "set_pseudo_wire_class": "pseudo_wire_class", "set_pseudowires": "pseudowire", "set_service_instances": 'service_instances', "set_template_type_pseudowires": "template_type_pseudowires", "set_bridge_domains": "bridge_domains", "set_vfis": "vfis" } self.excute_methods(methods=methods, devices=cisco_sources.values()) for tunnel_instance, tunnel in mpls_te_data.items(): if (tunnel["source_ip"] not in cisco_sources): cisco_sources[tunnel["source_ip"]] = CiscoIOS( master=self.master, ip=tunnel["source_ip"], display_name=tunnel["source_ip"]) device = cisco_sources[tunnel["source_ip"]] service_instance_data = device.get_service_instance_by_tunnel_id( tunnel_id=tunnel["tunnel_id"]) if (service_instance_data != "null"): tunnel["root_interface"] = service_instance_data["interface"] tunnel["root_service_instance"] = service_instance_data[ "service_instance"] tunnel["root_description"] = service_instance_data[ "description"] tunnel["root_dot1q"] = service_instance_data["dot1q"] else: service_instances_vfi = device.get_service_instance_by_tunnel_id_vfi( tunnel_id=tunnel["tunnel_id"]) tunnel["root_interface"] = "" tunnel["root_service_instance"] = "" tunnel["root_description"] = "" tunnel["root_dot1q"] = "" pprint("interfaces VFI") if service_instances_vfi: for service_instance_data in service_instances_vfi: tunnel["root_interface"] += service_instance_data[ "interface"] + " ! " tunnel[ "root_service_instance"] += service_instance_data[ "service_instance"] + " ! " tunnel["root_description"] += service_instance_data[ "description"] + " ! " tunnel["root_dot1q"] += service_instance_data[ "dot1q"] + " ! " # pprint(mpls_te_data) self.save_to_excel_dict(mpls_te_data, filename)
def devices_from_ip_list(self, list_devices_ip): devices = [] for ip in list_devices_ip: device = CiscoIOS(ip, "ios", self.master) devices.append(device) return devices
from model.InternetServiceProvider import InternetServiceProvider as ISP from config.Master import Master from model.CiscoIOS import CiscoIOS from model.CiscoXR import CiscoXR import time from pprint import pprint from model.Devices import Devices isp = ISP() isp.master = Master() isp.master.username = "******" isp.master.password = "******" ips = [line.replace("\n", "") for line in open("hosts/interfaces/guatemala")] # devs = Devices(master=isp.master,ip_list=ips,check_up=False) # devs.execute_processes(methods=["fix_interfaces_attr"],thread_window=20) c = CiscoIOS(ip="172.17.22.53", master=isp.master, display_name="") p2ps, routers = c.ospf_area_adjacency_p2p(area="504002", process_id="504") with open("hn_ips", "w") as f: f.write("\n".join(routers))
help='ip del dipositivo') parser.add_argument('ip_gateway', type=str, help='ip para hacerle salto') parser.add_argument('--vrf', type=str,nargs='?', help='vrf') parser.add_argument('--ig', type=str,nargs='?', help='jump gateway') parser.add_argument('filename', type=str, help='nombre del archivo') args = parser.parse_args() ''' claro = Claro() master = Master() test = CiscoIOS("10.240.233.154", "XR", master) # test.set_jump_gateway("10.250.55.3", protocol="telnet") # test3 = CiscoIOS("172.17.28.110", "XR", master) # test2 = CiscoXR("172.16.30.253", "XR", master) # test2.set_snmp_community() # test2.set_yed_xy() # print(test2.x) claro.master = master # xrs = CiscoXR.devices(master) data = test.create_file_nagios_arp() with open("nagios_co_wbp.txt", "w") as f: f.write(data)
def json_interface(): request.get_json() uid = request.json['uid'] start_date = request.json['date_start'] if start_date == "": start_date = str(datetime.datetime.today()).split(' ')[0] + " 00:00:00" end_date = request.json['date_end'] if end_date == "": end_date = str(datetime.datetime.today()).split(' ')[0] + " 23:59:59" interface = CiscoIOS.get_device_interface_uid(master=master, uid_interface=uid) interface_data = interface.get_interface_states_by_date( initial_date=start_date, end_date=end_date) out_data = [float(state['util_out']) for state in interface_data] in_data = [float(-1 * state['util_in']) for state in interface_data] dates = [str(state['state_timestamp']) for state in interface_data] in_percentil_data = list(reversed(sorted(in_data))) in_percentil = in_percentil_data[int(len(in_percentil_data) * .95)] out_percentil_data = list(sorted(out_data)) out_percentil = out_percentil_data[int(len(out_percentil_data) * .95)] in_percentil_line = [in_percentil for state in interface_data] out_percentil_line = [out_percentil for state in interface_data] print(in_percentil_line) print(out_percentil_line) interface_d = { 'name': f'{interface.parent_device.hostname} {interface.if_index} {interface.description}', 'if_index': interface.if_index, 'device': interface.parent_device.hostname, 'description': interface.description, 'out': { 'fill': 'tozeroy', 'type': 'scatter', 'x': dates, 'y': out_data }, 'down': { 'type': 'line', 'x': dates, 'y': in_percentil_line, 'color': 'red', 'name': ' 95% percentile in' }, 'in': { 'x': dates, 'y': in_data, 'fill': 'tozeroy', 'type': 'scatter' }, 'up': { 'type': 'line', 'x': dates, 'y': out_percentil_line, 'color': 'red', 'name': '95% percentile out' } } return jsonify(interface_d)
class L3Path: def __init__(self, network_model, device_ip, prefix, vrf="null", parent="null"): self.state = "init" self.network_model = network_model self.device_ip = device_ip self.device = CiscoIOS(self.device_ip, self.device_ip, self.network_model.master) self.prefix = prefix self.ip_route = "null" self.vrf = vrf self.parent_path = parent self.next_hops = {} self.incoming_interfaces = [] def init_path(self): if self.network_model.check_device_able_connect(self.device): self.device = self.network_model.correct_device_platform( [self.device])[0] if (type(self.device) is str): self.state = "dead_end_unable_connect" else: self.device.diplay_name = self.device.hostname self.state = "device_ready" else: self.state = "dead_end_unable_connect" return self.state def set_paths(self): self.set_reverse_path() connection = self.device.connect() ip_route = IpRoute.get_instance_route(connection=connection, parent_device=self.device, prefix=self.prefix, vrf=self.vrf) while ip_route.protocol == "bgp": ip_route = IpRoute.get_instance_route( connection=connection, parent_device=self.device, prefix=ip_route["paths"][0]["next_hop"], vrf="null") if (ip_route.has_paths()): if (ip_route.protocol != "ospf"): self.state = "dead_end_" + self.protocol else: self.device.set_ip_ospf_interfaces() # print(self.device.ospf_interfaces) for path in ip_route.paths: if (path["out_interface"] in self.device.ospf_interfaces): ip_ospf_id_next_hop = self.device.ospf_interfaces[ path["out_interface"]]["ospf_neighbor"] if (ip_ospf_id_next_hop != "0.0.0.0"): if self.check_path_in_parent( ip_ospf_id_next_hop) == False: if self.check_path_in_self( ip_ospf_id_next_hop) == False: l3path = L3Path(self.network_model, ip_ospf_id_next_hop, self.prefix, vrf="null", parent=self) self.next_hops[ip_ospf_id_next_hop] = { "L3Path": l3path, "interfaces": [path["out_interface"]] } self.state = "has_next_hop" else: self.next_hops[ip_ospf_id_next_hop][ "interfaces"].append( path["out_interface"]) else: self.state = "dead_end_already_in_path" else: self.state = "dead_end_no_ospf_neighbor" def search_recursive_path_route(self): self.init_path() if (self.state == "device_ready"): self.set_paths() # print(self.next_hops) for ip, next_hops in self.next_hops.items(): next_hops["L3Path"].search_recursive_path_route() def check_path_in_self(self, ip_next_hop): # print("adenntro del check") return ip_next_hop in self.next_hops def check_path_in_parent(self, ip_next_hop): # print("adenntro del padre") if (self.parent_path != "null"): return self.parent_path.check_path_all(ip_next_hop) else: return False def check_path_all(self, ip_next_hop): return self.check_path_in_self( ip_next_hop=ip_next_hop) or self.check_path_in_parent( ip_next_hop=ip_next_hop) def string_path(self, hop=0): hop += 1 output = "" if (hop == 1): output += "Prefix search " + " " + str(self.prefix) + "\n" output += "******hop count " + str(hop) + "*******\n" output += "Device ip " + self.device.ip + " " + self.state + "\n" output += "Incoming Interfaces" + "\n" for incoming_interface in self.incoming_interfaces: output += incoming_interface + "||" output += "\n" output += "Outgoing paths \n" for ip_next_hop, path in self.next_hops.items(): output += "next hop path " + ip_next_hop + "\n" output += "out interfaces: " for interface in path["interfaces"]: output += interface + "||" output += "\n" output += path["L3Path"].string_path(hop) return output def set_reverse_path(self): if (self.parent_path != "null"): connection = self.device.connect() ip_route = IpRoute.get_instance_route( connection=connection, parent_device=self.device, prefix=self.parent_path.device.ip, vrf=self.vrf) for path in ip_route.paths: self.incoming_interfaces.append(path["out_interface"]) return connection return "null" def set_method_recursive_thread(self, method, threads=[], kwargs={}): set_method_instantiated = getattr(self, method) t = threading.Thread(target=set_method_instantiated, kwargs=kwargs) t.start() threads.append(t) for ip_next_hop, path in self.next_hops.items(): path["L3Path"].set_method_recursive_thread(method, threads, kwargs) if self.parent_path == "null": for t in threads: t.join() return 1 def set_interfaces_stats(self): interfaces = [] if self.state != "dead_end_unable_connect": interfaces = interfaces + self.incoming_interfaces for ip_next_hop, path in self.next_hops.items(): interfaces = interfaces + path["interfaces"] self.device.set_interfaces_stats(interfaces_index=interfaces) return len(interfaces) def present_interfaces_stats(self): interfaces = [] output = "" if self.state != "dead_end_unable_connect": output = "////////////////////////////////\n" output += " HOP " + self.device.ip + " Incoming interface \n" output += self.device.get_interfaces_stats( interfaces_index=self.incoming_interfaces) output += " output interfaces \n" for ip_next_hop, path in self.next_hops.items(): output += self.device.get_interfaces_stats( interfaces_index=path["interfaces"]) return output def present_method_recursive(self, method): get_method_instantiated = getattr(self, method) output = get_method_instantiated() for ip_next_hop, path in self.next_hops.items(): output += path["L3Path"].present_method_recursive(method) return output def get_interfaces_stats(self): self.set_method_recursive_thread("set_interfaces_stats") output = self.present_method_recursive("present_interfaces_stats") return output def set_log(self, filter=""): self.device.set_log(filter) def get_log(self, filter=""): self.set_method_recursive_thread(method="set_log", kwargs={"filter": filter}) self.present_log_recursive() def present_log_recursive(self, logs={}, save_xls=True): logs[self.device.ip] = self.device.get_log() for ip_next_hop, path in self.next_hops.items(): path["L3Path"].present_log_recursive(logs, save_xls) # print(logs.keys()) if (save_xls and self.parent_path == "null"): file_name = "show logg path " + self.prefix + str( time.strftime(" %Y_%m_%d_%H_%M_%S")) + ".xls" print("saved_log to:" + file_name) workbook = xlwt.Workbook() for sheet, log in logs.items(): worksheet = workbook.add_sheet(sheetname=sheet) rows_skipped = 2 # Write rows for rowidx, row in enumerate(log): worksheet.write(rowidx + rows_skipped + 1, 1, row) workbook.save(filename_or_stream=file_name) '''
from model.InternetServiceProvider import InternetServiceProvider as ISP from config.Master import Master from model.CiscoIOS import CiscoIOS from model.CiscoXR import CiscoXR import time ip = '172.16.30.44' new_abr_ip = '172.16.30.251' abr_ip = '172.16.30.44' isp = ISP() isp.master = Master() suffix_path = "VPL9K_MIG" cisco = CiscoIOS(ip=ip, display_name="", master=isp.master) isp.excute_methods({ "set_mpls_te_tunnels": {}, "set_ip_explicit_paths": {} }, devices=[cisco]) data2 = isp.replace_loose_mpls_te_paths( abr_ip=abr_ip, new_abr_ip=new_abr_ip, devices=["172.16.30.44", "172.16.30.45"], suffix_path=suffix_path) with open(f"{cisco.ip}_loose.txt", "w") as f: data = f'------------------\n{cisco.ip}\n' data += data2 f.write(data)