def getAsnPeerListFromJunos(self, cfg): parse = CiscoConfParse("%s" % cfg, syntax='junos', comment='#') intf_data = self.getInterfaceListFromJunos(parse, cfg) #logger.warning("INTF_DATA:%s" % intf_data) peer_list_obj = parse.find_objects(" peer-as") peer_list = [] logger.warning("CFG_JUNOS: %s" % cfg) for peer in peer_list_obj: if not peer.text in peer_list: peer_list.append(peer.text) #logger.warning("PEER_LIST:%s" % peer_list) for peer in peer_list: PEER = {} PEER["asn"] = "" PEER["remote_neighbors"] = [] peer_ip = "" remote_neighbors = parse.find_parents_w_child(r" neighbor ", peer) #intf_data = {} for neighbor in remote_neighbors: peer_ip = re.sub(r"\s+|neighbor", "", neighbor) peer_info = self.getPeerInterfaceSubnetJunos( intf_data, peer_ip) #logger.warning("PEER_INFO_1:%s" % peer_info) if intf_data is not None: PEER["remote_neighbors"].append(peer_info) if len(PEER["remote_neighbors"]) == 0: #if PEER["remote_neighbors"] is None: peer_as_parents = parse.find_parents_w_child(r"group", peer) for parent in peer_as_parents: remote_neighbors = parse.find_children_w_parents( parent, r" neighbor ") for neighbor in remote_neighbors: peer_ip = re.sub(r"\s+|neighbor", "", neighbor) peer_info = self.getPeerInterfaceSubnetJunos( intf_data, peer_ip) #logger.warning("PEER_INFO_2:%s" % peer_info) if peer_info is not None: #PEER["remote_neighbors"].append(re.sub(r"\s+|neighbor", "", neighbor)) PEER["remote_neighbors"].append(peer_info) #if not PEER["remote_neighbors"] is None : if not len(PEER["remote_neighbors"]) == 0: PEER["asn"] = re.sub(r"\s+|peer-as", "", peer) ACTIVE_PEERS.append(PEER) logger.warning("%s" % (ACTIVE_PEERS)) with open("%s/%s.json" % (self.json_dir, re.sub(r".cfg$", "", cfg)), 'w') as outjsonfile: json.dump(ACTIVE_PEERS, outjsonfile) ACTIVE_PEERS.clear()
class DhcpConfig: def __init__(self, config_file): self.config_file = config_file self.parse = CiscoConfParse(self.config_file) def get_dhcppool_config(self, pool_name): find_result = self.parse.find_children(pool_name) return find_result def get_dhcppoolname_list(self): dhcppoolname_list = [] find_result = self.parse.find_parents_w_child('^ip dhcp pool', 'host') for parent in find_result: dhcppoolname_list.append(parent.split()[3]) return dhcppoolname_list def get_ipaddr(self, pool_name): find_result = self.parse.find_children(pool_name) return find_result[1].split()[1] def get_ipaddrmask(self, pool_name): find_result = self.parse.find_children(pool_name) return find_result[1].split()[2] def get_macaddr(self, pool_name): find_result = self.parse.find_children(pool_name) return find_result[2].split()[1] def get_defaultrouter(self, pool_name): find_result = self.parse.find_children(pool_name) return find_result[3].split()[1] def get_dns(self, pool_name): find_result = self.parse.find_children(pool_name) return [find_result[4].split()[1], find_result[4].split()[2]]
def main() : parse = CiscoConfParse("cisco_ipsec.txt") # Find all crypto map entries and print parent and child print ("The crypto maps in the parsed config are : \n" ) crypto_objs = parse.find_objects(r"^crypto map CRYPTO") for obj in crypto_objs : print (obj.text) child_obj = (obj.re_search_children(r".*")) for obj2 in child_obj : print (obj2.text) print ("\n") # Find crypto maps with pfs group2 pfsg2 = parse.find_parents_w_child("crypto map CRYPTO", "set pfs group2" ) print ("The following crypto maps have pfs set to group 2: \n") for obj in pfsg2 : print (obj) # Find crypto maps without AES encryptions print ("\n") trans_set = parse.find_parents_wo_child("^crypto map CRYPTO", "set transform-set AES-SHA") print ("The crypto maps that do not have AES-SHA transform set are : \n") for obj in trans_set : print (obj)
def parse_policy(policy, configFile): parse = CiscoConfParse(configFile) if policy[0]: object = parse.find_parents_w_child(policy[0], policy[1]) else: object = parse.find_objects(policy[1]) return object
def cisco_conf_task_2(): print "\n\nCisco parse exersise 2.\n" cfg_file = CiscoConfParse("cisco_ipsec.txt") c_maps = cfg_file.find_parents_w_child("^crypto map CRYPTO","^ set pfs group2") x = 1 for element in c_maps: print "entry # %s that are using PFS group2: %s" % (x, element) x += 1
def ios_get_list_vrf(conf_file): parse = CiscoConfParse(conf_file) #print parse.find_parents_w_child("^ip vrf ", "rd") #print list_vrf_buffer #buff = [] return { x.replace('ip vrf ', '') for x in parse.find_parents_w_child("^ip vrf ", "rd") }
def downloadRoustesForClient(self, client): #config_files_dir = self.config_files_dirs[country] data = {'BRASIL': [], 'MEXICO': []} countryDirList = os.listdir(self.root) for countryDir in countryDirList: countryDirPath = os.path.join(self.root, countryDir) peList = os.listdir(countryDirPath) print(countryDir) bar = progressbar.ProgressBar() for pe in bar(peList): pePath = os.path.join(countryDirPath, pe) with open(pePath) as pe_config: if ".txt" in pe: pe = pe.split(".txt")[0] parse = CiscoConfParse(pe_config) interfaces = parse.find_parents_w_child("^interface", client.get_vrf()) if interfaces: for interface in interfaces: wan = '' inter_config = parse.find_all_children("^%s$" % interface) inter_config_string = " ".join(inter_config) if 'vrf' not in inter_config_string or 'address' not in inter_config_string: continue for line in inter_config: line = line.split() # print(line) if 'vrf' in line: vrf = line[-1] elif 'address' in line: if line[-2] != 'address': wan = line[-2] else: wan = line[-1][:-4] # print(data[f]['wan'], f) wan = generate_ip(wan) if not wan: continue country = Country.objects.get(name=countryDir) if is_xr(pe_config.read()): routes = get_config(country, pe, "show bgp vrf " + vrf + " nei " + wan + " route", list=False) else: routes = get_config(country, pe, "show ip bgp vpnv4 vrf " + vrf + " nei " + wan + " route", list=False) routes = re.findall("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}", routes) if not routes: continue [data[countryDir].append(route) for route in routes] client.routes = data client.save() print('Done') return data
def cisco_conf_parse_parents(parent, child, config): """ Use CiscoConfParse to find parent lines that contain a specific child line. :param parent: The parent line to search for :param child: The child line required under the given parent :param config: The device running/startup config """ if type(config) == str: config = config.splitlines() parse = CiscoConfParse(config) cfg_obj = parse.find_parents_w_child(parent, child) return cfg_obj
def main(): #YAML file cisco_cfg = CiscoConfParse("./cisco_file.txt") print 'One way of doing it: find_parents_w_child' crypto_w_pfs2 = cisco_cfg.find_parents_w_child(r"^crypto map ", r"set pfs group2") print ' Result is type:', type(crypto_w_pfs2) print ' crypto_w_pfs2 is:', crypto_w_pfs2 for item in crypto_w_pfs2: print ' ', item print '\nA different way of doing it:find_objects_w_child' crypto_w_pfs2 = cisco_cfg.find_objects_w_child(r"^crypto map ", r"set pfs group2") print ' Result is type:', type(crypto_w_pfs2) print ' crypto_w_pfs2 is:', crypto_w_pfs2 for item in crypto_w_pfs2: print ' ', item.text
def getAsnPeerListFromIosXR(self, cfg): parse = CiscoConfParse("%s" % cfg, syntax='ios', comment='!', factory=True) intf_data = self.getInterfaceListFromIosXR(parse, cfg) peer_list_obj = parse.find_objects("^ remote-as") peer_list = [] logger.warning("CFG_IOSXR: %s" % cfg) for peer in peer_list_obj: if not peer.text in peer_list: peer_list.append(peer.text) logger.warning("%s" % peer_list) for peer in peer_list: PEER = {} PEER["asn"] = "" PEER["remote_neighbors"] = [] peer_ip = "" remote_neighbors = parse.find_parents_w_child(r"^ neighbor ", peer) logger.warning("REMOTE_NEIGHBORS=%s" % remote_neighbors) for neighbor in remote_neighbors: peer_ip = re.sub(r"\s+|neighbor", "", neighbor) peer_info = self.getPeerInterfaceSubnetIosXR( intf_data, peer_ip) if peer_info is not None: PEER["remote_neighbors"].append(peer_info) if not len(PEER["remote_neighbors"]) == 0: PEER["asn"] = re.sub("\s+|remote-as", "", peer) ACTIVE_PEERS.append(PEER) logger.warning("%s" % (ACTIVE_PEERS)) with open("%s/%s.json" % (self.json_dir, re.sub(r".cfg$", "", cfg)), 'w') as outjsonfile: json.dump(ACTIVE_PEERS, outjsonfile) ACTIVE_PEERS.clear()
def ios_has_vrf(conf_file): parse = CiscoConfParse("before.txt") if not parse.find_parents_w_child("^ip vrf ", "rd"): return False return True
class C(object): """ Classe permettant la correction / notation d'une configuration cisco """ def __init__(self, xml_path, conf_path): """ Initialisation des attributs de la classe. Attributs : root Fichier XML parsé conf Configuration cisco parsée """ self.root = etree.parse(xml_path).getroot() self.conf = CiscoConfParse(conf_path, syntax='ios') def print_xml(self): """ Affiche le contenu de tous les noeuds "tests" du fichier XML """ for child in self.root: for elem in child: print(elem.tag, elem.text) print("") def check_misc(self, node): """ Vérifie si un motif est présent dans la configuration réseau Exemple : 'service password-encryption' """ res = True for elem in node: if (elem.tag == 'motif'): if (len(self.conf.find_objects(elem.text)) == 0): res = False return res def check_node(self, parent, node): """ Vérifie si un/des motif(s) est/sont présent(s) sous un node parent Exemple : parent : 'Interface FastEthernet 0/0' motif : 'ip address 172.16.17.1 255.255.255.0' Vérifie que l'adresse IP ci-dessus il bien configurée dans l'interface fa0/0 Il est possible de vérifier des configurations d'interface, OSPF, IS-IS, EIGRP, RIP, BGP, line Comment ça marche ? Pour chaque 'enfant', on va chercher une liste des parents. Par exemple si 'transport input ssh' et 'login local' sont des motifs recherchés et sont configurés sur 'line vty 0 4' et 'line vty 5 15', alors on sort une liste l_result qui contient ces deux derniers. [[line vty 0 4, line vty 5 15], [line vty 0 4, line vty 5 15]] Si 'login local' n'est pas rentré sur 'line vty 5 15', alors la liste sera [[line vty 0 4, line vty 5 15], [line vty 0 4]] Puis on vérifie que le 'parent' du formulaire est bien présent dans chaque liste l dans l_result. Pourquoi l_result contient des listes ? Parce que 'find_parents_w_child' ressort tous les parents qui contiennent le motif recherchés, on doit donc vérifier que notre parent est présent dans chaque liste, pour s'assurer que toutes les motifs enfants sont bien rentrés sous ce parent. """ result = node.find('parent').text l_result = [] for elem in node: if (elem.tag == 'motif'): l_result.append( self.conf.find_parents_w_child(parent, elem.text)) # print(l_result) res = True for l in l_result: if result not in l: res = False return res def assess(self): """ Fait appel aux fonctions de recherches de motifs et note l'étudiant en fonctions des points définis dans le formulaire selon la présence ou non du motif donné """ points = 0 for child in self.root: for elem in child: if (elem.tag == 'type'): if (elem.text == 'misc'): if (self.check_misc(child)): points += int(child.find('points').text) else: if (self.check_node(elem.text, child)): points += int(child.find('points').text) """ if(elem.text == 'interface configuration'): if(self.check_node('interface', child)): points += int(child.find('points').text) if(elem.text == 'ospf configuration'): if(self.check_node('router ospf', child)): points += int(child.find('points').text) if(elem.text == 'isis configuration'): if(self.check_node('router isis', child)): points += int(child.find('points').text) if(elem.text == 'eigrp configuration'): if(self.check_node('router eigrp', child)): points += int(child.find('points').text) if(elem.text == 'rip configuration'): if(self.check_node('router rip', child)): points += int(child.find('points').text) if(elem.text == 'bgp configuration'): if(self.check_node('router bgp', child)): points += int(child.find('points').text) if(elem.text == 'line configuration'): if(self.check_node('line', child)): points += int(child.find('points').text) """ return points
#!/usr/bin/env python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("../configs/sample_01.ios") # Return a list of all ATM interfaces and subinterfaces atm_intfs = parse.find_lines("^interface\sATM") # Return a list of all interfaces with a certain QOS policy qos_intfs = parse.find_parents_w_child( "^interf", "service-policy" ) # Return a list of all active interfaces (i.e. not shutdown) active_intfs = parse.find_parents_wo_child( "^interf", "shutdown" )
def ios_get_vrf_related(conf_file, vrf_name): parse = CiscoConfParse(conf_file) parse.find_parents_w_child("^ip vrf " + vrf_name, "rd")
#!/usr/bin/env python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("../configs/sample_01.ios") # Return a list of all ATM interfaces and subinterfaces atm_intfs = parse.find_lines("^interface\sATM") # Return a list of all interfaces with a certain QOS policy qos_intfs = parse.find_parents_w_child("^interf", "service-policy") # Return a list of all active interfaces (i.e. not shutdown) active_intfs = parse.find_parents_wo_child("^interf", "shutdown")
def parse_intTRUNK(file): parse = CiscoConfParse(file) trunks = parse.find_parents_w_child("^interface", "switchport trunk") for intf in trunks: print(intf)
__author__ = "Bassim Aly" __EMAIL__ = "*****@*****.**" from ciscoconfparse import CiscoConfParse from pprint import pprint # EX1: Find All shutdown interfaces. orig_config = CiscoConfParse( "/media/bassim/DATA/GoogleDrive/Packt/EnterpriseAutomationProject/Chapter5_Extract_useful_data_from_network_devices/Cisco_Config.txt" ) shutdown_intfs = orig_config.find_parents_w_child(parentspec=r"^interface", childspec='shutdown') pprint(shutdown_intfs) # EX2: Does this configuration has a router from ciscoconfparse import CiscoConfParse from pprint import pprint orig_config = CiscoConfParse( "/media/bassim/DATA/GoogleDrive/Packt/EnterpriseAutomationProject/Chapter5_Extract_useful_data_from_network_devices/Cisco_Config.txt" ) check_router = orig_config.has_line_with(r"^router") pprint(check_router) # -- from ciscoconfparse import CiscoConfParse
class C(object): """ Classe permettant la correction / notation d'une configuration cisco """ def __init__(self, xml_path, conf_path): """ Initialisation des attributs de la classe. Attributs : root Fichier XML parsé conf Configuration cisco parsée """ self.root = etree.parse(xml_path).getroot() self.conf = CiscoConfParse(conf_path, syntax='ios') def print_xml(self): """ Affiche le contenu de tous les noeuds "tests" du fichier XML """ for child in self.root: for elem in child: print(elem.tag, elem.text) print("") def check_misc(self, node): """ Vérifie si un motif est présent dans la configuration réseau Exemple : 'service password-encryption' """ res = True for elem in node: if (elem.tag == 'motif'): if (len(self.conf.find_objects(elem.text)) == 0): res = False return res def check_node(self, parent, node): """ Vérifie si un/des motif(s) est/sont présent(s) sous un node parent Exemple : parent : 'Interface FastEthernet 0/0' motif : 'ip address 172.16.17.1 255.255.255.0' Vérifie que l'adresse IP ci-dessus il bien configurée dans l'interface fa0/0 Il est possible de vérifier des configurations d'interface, OSPF, IS-IS, EIGRP, RIP, BGP, line """ result = node.find('parent').text l_result = [] for elem in node: if (elem.tag == 'motif'): l_result.append( self.conf.find_parents_w_child(parent, elem.text)) # print(l_result) res = True for l in l_result: if result not in l: res = False return res def assess(self): """ Fait appel aux fonctions de recherches de motifs et note l'étudiant en fonctions des points définis dans le formulaire selon la présence ou non du motif donné """ points = 0 for child in self.root: for elem in child: if (elem.tag == 'type'): if (elem.text == 'misc'): if (self.check_misc(child)): points += int(child.find('points').text) else: if (self.check_node(elem.text, child)): points += int(child.find('points').text) """ if(elem.text == 'interface configuration'): if(self.check_node('interface', child)): points += int(child.find('points').text) if(elem.text == 'ospf configuration'): if(self.check_node('router ospf', child)): points += int(child.find('points').text) if(elem.text == 'isis configuration'): if(self.check_node('router isis', child)): points += int(child.find('points').text) if(elem.text == 'eigrp configuration'): if(self.check_node('router eigrp', child)): points += int(child.find('points').text) if(elem.text == 'rip configuration'): if(self.check_node('router rip', child)): points += int(child.find('points').text) if(elem.text == 'bgp configuration'): if(self.check_node('router bgp', child)): points += int(child.find('points').text) if(elem.text == 'line configuration'): if(self.check_node('line', child)): points += int(child.find('points').text) """ return points
# Script to find what interfaces have an "ip helper-address" # Uses ciscoconfparse library, make sure its installed #Importing the necessary modules. import os from ciscoconfparse import CiscoConfParse os.chdir("c:\\configs") for filename in os.listdir(os.getcwd()): parse = CiscoConfParse(filename, factory=True, syntax='ios') obj_list = parse.find_objects_dna(r'Hostname') inf_w_help = parse.find_parents_w_child(parentspec=r"^interface", childspec=r"ip helper-address") hostn = obj_list[0].hostname print hostn for interface in inf_w_help: print interface print("Write results to file...") newconfig = CiscoConfParse([]) newconfig.append_line(hostn) for interface in inf_w_help: newconfig.append_line(interface) newconfig.append_line('ip helper-address my.new.ip.add1') newconfig.commit() newconfig.save_as(hostn + '_newconfig.txt')
def testValues_find_parents_w_child(self): ## test find_parents_w_child for config, args, result_correct in self.find_parents_w_child_Values: cfg = CiscoConfParse(config) test_result = cfg.find_parents_w_child(**args) self.assertEqual(result_correct, test_result)
def update_config(template, parse): logger.info("update_config function") #parse template logger.debug("update_config: template: {}".format(template)) tparse1 = CiscoConfParse(template.splitlines()) logger.debug("update_config: tparse1: {}".format(tparse1)) #get all objects objs1 = tparse1.find_objects('.*') logger.debug(objs1) #check for parents par1 = tparse1.find_parents_w_child('.*', '.*') logger.debug("update_config: parents in template: {}".format(par1)) for obj in objs1: logger.debug("update_config: obj: {}".format(obj)) logger.debug("is_parent: {}".format(obj.is_parent)) logger.debug("is_child: {}".format(obj.is_child)) if not obj.is_parent and not obj.is_child: logger.debug("obj {} is not parent or child".format(obj)) if not parse.find_objects(r"^{}\s*$".format(obj.text)): parse.append_line(obj.text) parse.commit() if par1: for parent in par1: logger.debug("== parent {} ==".format(parent)) children = tparse1.find_children_w_parents( r"^{}\s*$".format(parent), r'.*') logger.debug("children: {}".format(children)) cobj = parse.find_objects(r"^{}\s*$".format(parent)) logger.debug(cobj) if cobj: cobj = cobj[0] logger.debug("== cobj {} ==".format(cobj)) if cobj.is_parent: logger.debug("update_config: cobj.is_parent") children.reverse() for child in children: logger.debug( "update_config: parent: child: {}".format(child)) if not cobj.has_child_with(r"{}\s*$".format(child)): logger.debug( "update_config: cobj not have child: {}, writing line" .format(child)) cobj.append_to_family(child) else: logger.debug("update_config: cobj is not parent") parse.insert_after(cobj.text, children[0]) parse.commit() previous = children[0] for child in children[1:]: logger.debug( "update_config: not parent: child: {}".format( child)) parse.insert_after(regex_modify(previous), child) previous = child parse.commit() else: logger.debug("== not cobj ==") parse.append_line(parent) parse.commit() previous = parent for child in children: logger.debug( "update_config: not cobj: child: {}".format(child)) #logger.debug(parse.find_objects(previous)) logger.debug( "update_config: not cobj: previous: {}".format( previous)) logger.debug(parse.find_objects(regex_modify(previous))) parse.insert_after(regex_modify(previous), child) previous = child parse.commit() parse.commit() return parse
#!/usr/bin/python #Import modules from ciscoconfparse import CiscoConfParse #Search through the config file parse = CiscoConfParse('conf.txt') basic_search = parse.find_parents_w_child('^interface', 'trunk') print basic_search #Save output to text file f = open('output.txt', 'w') print >> f, basic_search f.close() #Sanitize the output to replace , with a new line f = open('output.txt','r') filedata = f.read() f.close() newdata = filedata.replace(", ","\n") f = open('output.txt','w') f.write(newdata) f.close() #Sanitize he output for ' f = open('output.txt','r') filedata = f.read() f.close() newdata = filedata.replace("'","") f = open('output.txt','w') f.write(newdata)
nd = NetDevices() for deviceName in deviceList: # commands to run in order to bring the device back to standard commandList = [] # the current device configuration file is stored here, parse it p = CiscoConfParse("/home/ioswrite/network-configurations/" + deviceName) # --------------------------------------------------------------------------------- # STORM CONTROL: legacy switch configuration # --------------------------------------------------------------------------------- # give me a list of interfaces that contain " port storm-control unicast" interfaceList = p.find_parents_w_child('^interf', '^ port storm-control unicast') # create the commands so that I can remove this unwanted command for line in interfaceList: commandList.append(line) commandList.append(' no port storm-control unicast action filter') commandList.append(' no port storm-control unicast trap') # --------------------------------------------------------------------------------- # STORM CONTROL: modern switch configuration # --------------------------------------------------------------------------------- # give me a list of interfaces that contain "storm-control unicast level" interfaceList = p.find_parents_w_child('^interf', 'storm-control unicast level') # create the commands so that I can remove this unwanted command
def response_change(self, request, obj): if "update_cnr" in request.POST: obj.update_cnr() self.message_user(request, "The CNR was updated") return HttpResponseRedirect(".") elif "connect" in request.POST: if obj.config.hostname: import socket from ciscoconfparse import CiscoConfParse try: print( os.path.join(CONFIG_PATH, obj.country.name, obj.config.hostname.name + '.txt')) config = open( os.path.join(CONFIG_PATH, obj.country.name, obj.config.hostname.name + '.txt')) parser = CiscoConfParse(config) vrf_list = () if obj.config.hostname.os == 'ios': for line in parser.find_parents_w_child( "^ip vrf", "rd"): vrf = line.split(" ")[-1] vrf_list = vrf_list + (vrf, ) elif obj.config.hostname.os == 'xr': for line in parser.find_parents_w_child( "^vrf", "address-family"): vrf = line.split(" ")[-1] vrf_list = vrf_list + (vrf, ) server_ip = socket.gethostbyname(socket.gethostname()) port = request.META['SERVER_PORT'] file_loader = FileSystemLoader( os.path.join(os.path.dirname(__file__))) env = Environment(loader=file_loader, trim_blocks=True, lstrip_blocks=True) template = env.get_template('telmex_glass.py') template = template.render( pk=obj.pk, hostname=obj.config.hostname.name, os=obj.config.hostname.os, vrf_list=vrf_list, server_ip=server_ip, port=port) response = StreamingHttpResponse( template, content_type="application/py") response[ 'Content-Disposition'] = "attachment; filename=%s.py" % ( obj.config.hostname.name, ) return response except FileNotFoundError: self.message_user(request, "Config not found", level=messages.ERROR) return HttpResponseRedirect(".") elif "download_config" in request.POST: if obj.local_id: if obj.country.lg: try: hostname = Hostname.objects.get( local_ids__contains=[obj.local_id]) except: self.message_user( request, "This service's is not configured yet", level=messages.ERROR) return HttpResponseRedirect(".") if obj.country.name == 'COLOMBIA' and hostname.os == 'xr': config = get_config_from( obj.country, hostname.name, command='show configuration running-config') elif obj.country.name == 'COLOMBIA' and hostname.os == 'ios': config = get_config_from(obj.country, hostname.name, command='show configuration') elif obj.country.name == 'CHILE': config = get_config_from(obj.country, hostname.name, command='show star') else: config = get_config_from(obj.country, hostname.name) if config == INVALID_HOSTNAME: self.message_user(request, "Incorrect the hostname", level=messages.ERROR) elif config == CONNECTION_PROBLEM: self.message_user(request, "No VPN connection", level=messages.ERROR) elif config == INVALID_AUTH: self.message_user(request, "Wrong credentials", level=messages.ERROR) elif config == INVALID_COMMAND: self.message_user(request, "Invalid command", level=messages.ERROR) else: print('extracting config') interface_config = extract_info( config, obj, hostname, obj.country) print(interface_config) if interface_config: print('saving') config_model, created = Configuration.objects.get_or_create( hostname=hostname, link=obj) config_model.update(interface_config) if created: obj.configuration = config_model obj.save() obj.customer.add_vrf(config_model.vrf) print('saved') else: self.message_user( request, "This service's country doesnt have a LG", level=messages.ERROR) else: self.message_user(request, "Please specify a Local-ID", level=messages.ERROR) return HttpResponseRedirect(".") elif "template" in request.POST: if obj.config: file_loader = FileSystemLoader( os.path.join(os.path.dirname(__file__))) env = Environment(loader=file_loader, trim_blocks=True, lstrip_blocks=True) env.filters["convert_netmask"] = convert_netmask env.filters["format_speed"] = format_speed config = obj.config config.customer = obj.customer.name config.interface = obj.interface if obj.nsr[-1] == 'P': config.cm = '28513:285' else: config.cm = '28513:286' template = env.get_template('template.j2').render( config=config) output = create_template_excel(obj, template) response = StreamingHttpResponse( FileWrapper(output), content_type="application/vnd.ms-excel") response[ 'Content-Disposition'] = "attachment; filename=%s-%d-%s.xlsx" % ( obj.site_name, obj.pgla, obj.nsr) return response else: self.message_user( request, "Upload or manually enter the configuration specs", level=messages.ERROR) return HttpResponseRedirect(".") elif "rfs" in request.POST: rfs_excel = create_rfs(obj) response = StreamingHttpResponse( FileWrapper(rfs_excel), content_type="application/vnd.ms-excel") response[ 'Content-Disposition'] = "attachment; filename=PGLA-" + str( obj.pgla ) + "-" + obj.nsr + "-" + obj.movement.name + ".xlsx" return response elif "update" in request.POST: hostname = obj.config.hostname file_path = os.path.join(CONFIG_PATH, obj.country.name, obj.config.hostname.name) + '.txt' if obj.config.hostname.os == 'junos': config = get_config_from(obj.country, hostname.name, l=False) else: config = get_config_from(obj.country, hostname.name, command="show configuration", l=False) with io.open(file_path, 'w', encoding="ISO-8859-1") as file: print('Saved') file.write(config) hostname.mtime = datetime.fromtimestamp( os.path.getmtime(file_path)) hostname.save() return HttpResponseRedirect(".") elif "view_config" in request.POST: if obj.config.hostname: try: with open( os.path.join(CONFIG_PATH, obj.country.name, obj.config.hostname.name + ".txt")) as file: data = file.readlines() response = StreamingHttpResponse( data, content_type="application/txt") response[ 'Content-Disposition'] = "attachment; filename=%s.txt" % ( obj.config.hostname.name, ) return response except FileNotFoundError: self.message_user(request, "The config file was not found", level=messages.ERROR) return HttpResponseRedirect(".") else: return super().response_change(request, obj)
def Procurar_CCP(): print "------------------------------------------------------------------" print "1 - Pesquisa somente por Linha" print "2 - Pesquisa somente por Pai e Filho" print "3 - Pesquisa somente por Filhos de um mesmo Pai" print "------------------------------------------------------------------" op1_pes = str(raw_input("Qual Metodo de pesquisa deseja: ")) print "------------------------------------------------------------------" if op1_pes == "1": for arq in os.listdir('.'): print arq print "------------------------------------------------------------------" op1_pes = str(raw_input("Qual arquivo de pesquisa>> ")) try: op1_pes = "./" + op1_pes pes = CiscoConfParse(op1_pes) print "------------------------------------------------------------------" print "int = interface" print "por obj = colocar o nome do objecto" print "ip = para ip" print "Ou qualquer outra linha de comando" print "------------------------------------------------------------------" op2_pes = str(raw_input("Voce quer procurar por ?\n")) pes1 = pes.find_objects(op2_pes) print "------------------------------------------------------------------" print op1_pes.split("/")[len(op1_pes.split("/")) - 1] + ":" print "------------------------------------------------------------------" for resul in pes1: print resul.text except: print "Falha na abertura do arquivo favor verificar." print "------------------------------------------------------------------" main() elif op1_pes == "2": for arq in os.listdir('.'): print arq print "------------------------------------------------------------------" op1_pes = str(raw_input("Qual arquivo de pesquisa>> ")) print "------------------------------------------------------------------" try: op1_pes = "./" + op1_pes pes = CiscoConfParse(op1_pes) print "------------------------------------------------------------------" print "1 - interface" print "2 - object-group" #print "99 - Avancado" print "------------------------------------------------------------------" op2_pes = str(raw_input("Qual Pai voce quer procurar ?\n")) if op2_pes == "int" or op2_pes == "interface" or op2_pes == "inter" or op2_pes == "1": op3_pes = str(raw_input("Qual filho voce quer procurar ?\n")) pes1 = pes.find_parents_w_child("^inter", op3_pes) print "------------------------------------------------------------------" print op1_pes.split("/")[len(op1_pes.split("/")) - 1] + ":" print "------------------------------------------------------------------" for resul in pes1: print resul print "------------------------------------------------------------------" elif op2_pes == "obj" or op2_pes == "object" or op2_pes == "group" or op2_pes == "2": op3_pes = str(raw_input("Qual filho voce quer procurar ?\n")) pes1 = pes.find_parents_w_child("^object-group", op3_pes) print "------------------------------------------------------------------" print op1_pes.split("/")[len(op1_pes.split("/")) - 1] + ":" print "------------------------------------------------------------------" for resul in pes1: print resul print "------------------------------------------------------------------" else: main() except: pass elif op1_pes == "3": for arq in os.listdir('.'): print arq print "------------------------------------------------------------------" op1_pes = str(raw_input("Qual arquivo de pesquisa>> ")) print "------------------------------------------------------------------" try: op1_pes = "./" + op1_pes pes = CiscoConfParse(op1_pes) print "------------------------------------------------------------------" #print "1 - interface" print "1 - object-group" #print "99 - Avancado" print "------------------------------------------------------------------" op2_pes = str(raw_input("Qual Pai voce quer procurar ?\n")) if op2_pes == "obj" or op2_pes == "object" or op2_pes == "group" or op2_pes == "1": op3_pes = str( raw_input( "Qual o nome do grupo que voce quer ver as configuracoes ?\n" )) pes1 = pes.find_children_w_parents( "^object-group\snetwork\s" + op3_pes + "$", "net") print "------------------------------------------------------------------" print op1_pes.split("/")[len(op1_pes.split("/")) - 1] + ":" print "object-group network " + op3_pes print "------------------------------------------------------------------" for resul in pes1: print resul print "------------------------------------------------------------------" except: pass else: main() main()