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()
Exemple #2
0
def testVal_parse_F5():
    """Test for Github issue #49"""
    config = [
        'ltm virtual virtual1 {',
        '    profiles {',
        '        test1 { }',
        '    }',
        '}',
        'ltm virtual virtual2 {',
        '    profiles2 {',
        '        test2 { }',
        '    }',
        '}',
    ]
    parse = CiscoConfParse(config, syntax='junos')
    retval = parse.find_children_w_parents('ltm virtual virtual2',
                                           'profiles2')[0]
    assert retval == '    profiles2 '
print("Number of items in list: %s" % lint)
print("Routed Interfaces from config file: %s" % str(sys.argv[1]))

raw_input("Press Return to continue to IP Section...")

ipint = config.find_interface_objects("^interface")
lipint = len(ipint)
for i in ipint:
    print i

print("Number of items in list: %s" % lipint)
print("IPs from config file: %s" % str(sys.argv[1]))

raw_input("Press Return to continue to Other IP Section...")

ipint2 = config.find_children_w_parents("^interface\s", "ip address")
lipint2 = len(ipint2)
print ipint2
for i in ipint2:
    print i

print("Number of items in list: %s" % lipint2)
print("IPs from config file: %s" % str(sys.argv[1]))

raw_input("Press Return to continue to static routes...")

sroute = config.find_objects(r"^ip\sroute")
lsroute = len(sroute)
print sroute
for r in sroute:
    print r
Exemple #4
0
def ConfigParser(fileName):
    
    p = CiscoConfParse(fileName)
    text = ""

    DN = p.find_objects("^hostname")
    for DNtmp in DN:
        DeviceName = DNtmp.replace("hostname", "").lstrip()
    print "Please wait, your file is generated.........."
    workbook = xlsxwriter.Workbook(DeviceName + '.xlsx')

#####################################
#                                   #
#   Extracting Network Object       #
#                                   #
#####################################

    worksheet1 = workbook.add_worksheet('Object Network')
    row = 0
    col = 0

    worksheet1.write(row, col + 1, "Object Name")
    worksheet1.write(row, col + 2, "IP Address")
    worksheet1.write(row, col + 3, "Netmask")
    worksheet1.write(row, col + 4, "NAT")
    worksheet1.write(row, col + 5, "Description")
    row += 1
    
    # Looking for Object Network Type #
    for parents in p.find_objects(r"^object network"):
        tmpNetOBJ = parents.text
        #print (tmp)
        worksheet1.write(row, col + 1, tmpNetOBJ.replace("object network", "").lstrip())

        if parents.re_search_children("host"):
         for strs in p.find_children_w_parents(tmpNetOBJ, 'host'):
                host = strs.replace("host", "").lstrip()
                #print (host)
                worksheet1.write(row, col + 2, host)
                worksheet1.write(row, col + 3, "255.255.255.255")

        if parents.re_search_children("subnet"):
            for strs in p.find_children_w_parents(tmpNetOBJ, 'subnet'):
                ip = strs.replace("subnet", "").lstrip()
                address,netmask = ip.split()
                #network = address + '/' + str(iptools.ipv4.netmask2prefix(netmask))
                #print (subnet)
                worksheet1.write(row, col + 2, address)
                worksheet1.write(row, col + 3, netmask)

        if parents.re_search_children("fqdn"):
            for strs in p.find_children_w_parents(tmpNetOBJ, 'fqdn'):
                fqdn = strs.replace("fqdn v4", "").lstrip()
                #print (fqdn)
                worksheet1.write(row, col + 2, fqdn)
                worksheet1.write(row, col + 3, "-")

        if parents.re_search_children("range"):
            for strs in p.find_children_w_parents(tmpNetOBJ, 'range'):
                srange = strs.replace("range", "").lstrip()
                #print (fqdn)
                worksheet1.write(row, col + 2, srange.replace("range", "").lstrip())
                worksheet1.write(row, col + 3, "-")
                
        if not parents.re_search_children("description"):
            #print ("description none ")
            worksheet1.write(row, col + 5, "-")
        elif parents.re_search_children("description"):
            arry = []
            for child in p.find_children_w_parents("^%s$" % tmpNetOBJ, 'description', ignore_ws=True):
                string = child.lstrip()
                arry.append(string.replace("description", "").lstrip())
                #print (', '.join(arry))
            worksheet1.write(row, col + 5, ', '.join(arry))

        row += 1

    print ("Extracting Network Object Configuration : Completed")

#####################################
#                                   #
#   Extracting Service Object       #
#                                   #
#####################################

    worksheet2 = workbook.add_worksheet('Object Service')
    row = 0
    col = 0
    
    worksheet2.write(row, col + 1, "Object Name")
    worksheet2.write(row, col + 2, "TCP/UDP")
    worksheet2.write(row, col + 3, "Source Port")
    worksheet2.write(row, col + 4, "Destination Port")
    worksheet2.write(row, col + 5, "Description")
    row += 1    

    for parents in p.find_objects(r"^object service"):
        tmpServiceOBJ = parents.text
        #print (tmp)
        worksheet2.write(row, col + 1, tmpServiceOBJ.replace("object service", "").lstrip())

        if parents.re_search_children("service tcp destination eq"):
         for strs in p.find_children_w_parents(tmpServiceOBJ, 'service tcp destination eq'):
                service = strs.replace("service tcp destination eq", "").lstrip()
                #print (service)
                worksheet2.write(row, col + 2, "TCP")
                worksheet2.write(row, col + 3, "1-65535")
                worksheet2.write(row, col + 4, service)

        if parents.re_search_children("service tcp destination range"):
            for strs in p.find_children_w_parents(tmpServiceOBJ, 'service tcp destination range'):
                service = strs.replace("service tcp destination range", "").lstrip()
                #print (service)
                worksheet2.write(row, col + 2, "TCP Range")
                worksheet2.write(row, col + 3, "1-65535")
                worksheet2.write(row, col + 4, service)

        if parents.re_search_children("service udp destination eq"):
            for strs in p.find_children_w_parents(tmpServiceOBJ, 'service udp destination eq'):
                service = strs.replace("service udp destination eq", "").lstrip()
                #print (service)
                worksheet2.write(row, col + 2, "UDP")
                worksheet2.write(row, col + 3, "1-65535")
                worksheet2.write(row, col + 4, service)

        if parents.re_search_children("service udp destination range"):
            for strs in p.find_children_w_parents(tmpServiceOBJ, 'service udp destination range'):
                service = strs.replace("service udp destination range", "").lstrip()
                #print (service)
                worksheet2.write(row, col + 2, "UDP Range")
                worksheet2.write(row, col + 3, "1-65535")
                worksheet2.write(row, col + 4, service)                

        if parents.re_search_children("service icmp"):
            for strs in p.find_children_w_parents(tmpServiceOBJ, 'service icmp'):
                #service = strs.replace("service tcp destination range", "").lstrip()
                #print (service)
                worksheet2.write(row, col + 2, "ICMP")
                worksheet2.write(row, col + 3, "-")
                worksheet2.write(row, col + 4, "-")
                
        row += 1

    print ("Extracting Service Object Configuration : Completed")

##########################################
#                                        #
#   Extracting Network Object Group      #
#                                        #
##########################################

    worksheet3 = workbook.add_worksheet('Network Group Object')
    row = 0
    col = 0

    worksheet3.write(row, col + 1, "Group Name")
    worksheet3.write(row, col + 2, "Member Name")
    worksheet3.write(row, col + 3, "IP Address")
    worksheet3.write(row, col + 4, "Netmask")
    worksheet3.write(row, col + 5, "Control Number")
    worksheet3.write(row, col + 6, "Description")
    row += 1
    netobject = ""
    
    for parents in p.find_objects(r"^object-group network"):
        tmpNetOBJGroup = parents.text
        #worksheet3.write(row, col + 1, tmpNetOBJGroup.replace("object-group network", "").lstrip())
        #print (tmp)

        if parents.re_search_children("description"):
         for strs in p.find_children_w_parents(tmpNetOBJGroup, 'description'):
             description = strs.replace("description", "").lstrip()
             worksheet3.write(row, col + 1, tmpNetOBJGroup.replace("object-group network", "").lstrip())
             worksheet3.write(row, col + 6, description)
             
        if parents.re_search_children("network-object"):
         for strs in p.find_children_w_parents(tmpNetOBJGroup, 'network-object'):            
             netobject = strs.replace("network-object", "").lstrip()
             worksheet3.write(row, col + 1, tmpNetOBJGroup.replace("object-group network", "").lstrip())
             
             #print netobject
             if 'host' in netobject:
                 netobject = netobject.replace("host", "").lstrip()
                 network = address + "/32"
                 worksheet3.write(row, col + 2, network)
                 worksheet3.write(row, col + 3, netobject)
                 worksheet3.write(row, col + 4, "255.255.255.255")
                 #print netobject
             elif "object" in netobject:
                 netobject = netobject.replace("object", "").lstrip()
                 worksheet3.write(row, col + 2, netobject)
             else:
                 address,netmask = netobject.split()
                 network = address + '/' + str(iptools.ipv4.netmask2prefix(netmask))
                 worksheet3.write(row, col + 2, network)
                 worksheet3.write(row, col + 3, address)
                 worksheet3.write(row, col + 4, netmask)
                 #print netobject
             row += 1                            
                
    print ("Extracting Network Object Group Configuration : Completed")
 
##########################################
#                                        #
#   Extracting Network service Group     #
#                                        #
##########################################

    worksheet4 = workbook.add_worksheet('Service Group Object')
    row = 0
    col = 0

    worksheet4.write(row, col + 1, "Group Name")
    worksheet4.write(row, col + 2, "TCP/UDP")
    worksheet4.write(row, col + 3, "Source Port")
    worksheet4.write(row, col + 4, "Destination Port")
    row += 1
    
    for parents in p.find_objects(r"^object-group service"):
        tmpSVCOBJGroup = parents.text
        #print (tmp)
        groupname = tmpSVCOBJGroup.replace("object-group service", "").lstrip()
        if "tcp" in groupname:
          groupname = groupname.replace("tcp", "").lstrip()
          worksheet4.write(row, col + 2, "TCP")
        elif "udp" in groupname:
          groupname = groupname.replace("udp", "").lstrip()
          worksheet4.write(row, col + 2, "UDP")

        #worksheet4.write(row, col + 1, groupname)        
        #firstrow = row
        
        if parents.re_search_children("port-object eq"):
         for strs in p.find_children_w_parents(tmpSVCOBJGroup, 'port-object eq'):
                serviceobject = strs.replace("port-object eq", "").lstrip()
                worksheet4.write(row, col + 1, groupname) 
                worksheet4.write(row, col + 3, "1-65535")
                worksheet4.write(row, col + 4, serviceobject)
                row += 1
                
        if parents.re_search_children("port-object range"):
         for strs in p.find_children_w_parents(tmpSVCOBJGroup, 'port-object range'):
                serviceobject = strs.replace("port-object range", "").lstrip()
                worksheet4.write(row, col + 1, groupname) 
                worksheet4.write(row, col + 3, "1-65535")
                worksheet4.write(row, col + 4, serviceobject)
                row += 1
                
        if parents.re_search_children("service-object object"):
         for strs in p.find_children_w_parents(tmpSVCOBJGroup, 'service-object object'):
                servicegroupobject = strs.replace("service-object object", "").lstrip()
                worksheet4.write(row, col + 1, groupname) 
                worksheet4.write(row, col + 3, "1-65535")
                if ('tcp' or 'TCP') in servicegroupobject:
                    worksheet4.write(row, col + 2, "TCP")
                elif ('udp' or 'UDP') in servicegroupobject:
                    worksheet4.write(row, col + 2, "UDP")                           
                                    
                worksheet4.write(row, col + 4, servicegroupobject)
                row += 1

        if parents.re_search_children("service-object tcp"):
         for strs in p.find_children_w_parents(tmpSVCOBJGroup, 'service-object tcp destination'):
               service = strs.replace("service-object tcp destination", "").lstrip()
               worksheet4.write(row, col + 1, groupname) 
               worksheet4.write(row, col + 2, "TCP")
               worksheet4.write(row, col + 3, "1-65535")
               worksheet4.write(row, col + 4, service.replace("eq", ""))
               row += 1

        if parents.re_search_children("service-object udp"):
         for strs in p.find_children_w_parents(tmpSVCOBJGroup, 'service-object udp'):
               service = strs.replace("service-object udp destination", "").lstrip()
               worksheet4.write(row, col + 1, groupname) 
               worksheet4.write(row, col + 2, "UDP")
               worksheet4.write(row, col + 3, "1-65535")
               worksheet4.write(row, col + 4, service.replace("eq", ""))
               row += 1

        if parents.re_search_children("group-object"):
         for strs in p.find_children_w_parents(tmpSVCOBJGroup, 'group-object'):
               worksheet4.write(row, col + 1, groupname) 
               servicegroupobject = strs.replace("group-object", "").lstrip()
               worksheet4.write(row, col + 3, "1-65535")
               worksheet4.write(row, col + 4, 'Group ' + servicegroupobject)
               row += 1

              
    print ("Extracting Service Object Group Configuration : Completed")
 

##########################################
#                                        #
#   Extracting Access List               #
#                                        #
##########################################

    worksheet5 = workbook.add_worksheet('Access-List')
    row = 0
    col = 0

    worksheet5.write(row, col + 1, "Access List Name")
    worksheet5.write(row, col + 2, "Source")
    worksheet5.write(row, col + 3, "Destination")
    worksheet5.write(row, col + 4, "Service")
    worksheet5.write(row, col + 5, "Action")
    worksheet5.write(row, col + 6, "Remark")
    row += 1
    
    for parents in p.find_objects(r"^access-list"):
        tmp = parents.text.split()

        if 'remark' in tmp[2]:
			global remark
			remark = parents.text.split(' ', 3)
			worksheet5.write(row, col + 6, remark[3])
        
        if 'extended' in tmp[2]:
            if 'permit' in tmp[3]:
                worksheet5.write(row, col + 5, "Permit")
            elif 'deny' in tmp[3]:
                worksheet5.write(row, col + 5, "Deny")
            
            if "ip" in tmp[4]:
                if 'any' in tmp[5]:
                    worksheet5.write(row, col + 2, "Any")
                    if 'any' in tmp[6]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[6]:
                        worksheet5.write(row, col + 3, tmp[7])
                    elif 'host' in tmp[6]:
                        worksheet5.write(row, col + 3, tmp[7])
                    else:
                        worksheet5.write(row, col + 3, (tmp[6]+" "+tmp[7]))
                elif ('object' or 'object-group') in tmp[5]:
                    worksheet5.write(row, col + 2, tmp[6])
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                elif 'host' in tmp[5]:
                    worksheet5.write(row, col + 2, tmp[6])
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                else:
                    worksheet5.write(row, col + 2, (tmp[5]+" "+tmp[6]))
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                worksheet5.write(row, col + 4, "Any")

            elif "icmp" in tmp[4]:
                if 'any' in tmp[5]:
                    worksheet5.write(row, col + 2, "Any")
                    if 'any' in tmp[6]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[6]:
                        worksheet5.write(row, col + 3, tmp[7])
                    elif 'host' in tmp[6]:
                        worksheet5.write(row, col + 3, tmp[7])
                    else:
                        worksheet5.write(row, col + 3, (tmp[6]+" "+tmp[7]))
                elif ('object' or 'object-group') in tmp[5]:
                    worksheet5.write(row, col + 2, tmp[6])
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                elif 'host' in tmp[5]:
                    worksheet5.write(row, col + 2, tmp[6])
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                else:
                    worksheet5.write(row, col + 2, (tmp[5]+" "+tmp[6]))
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                worksheet5.write(row, col + 4, "ICMP")

            elif "tcp" in tmp[4]:
                if 'any' in tmp[5]:
                    worksheet5.write(row, col + 2, "Any")
                    if 'any' in tmp[6]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[6]:
                        worksheet5.write(row, col + 3, tmp[7])
                    elif 'host' in tmp[6]:
                        worksheet5.write(row, col + 3, tmp[7])
                    else:
                        worksheet5.write(row, col + 3, (tmp[6]+" "+tmp[7]))
                elif ('object' or 'object-group') in tmp[5]:
                    worksheet5.write(row, col + 2, tmp[6])
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 4, tmp[9])
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                        worksheet5.write(row, col + 4, tmp[10])
                elif 'host' in tmp[5]:
                    worksheet5.write(row, col + 2, tmp[6])
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 4, tmp[9])
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                        worksheet5.write(row, col + 4, tmp[10])
                else:
                    worksheet5.write(row, col + 2, (tmp[5]+" "+tmp[6]))
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                        worksheet5.write(row, col + 4, tmp[10])

            elif "udp" in tmp[4]:
                if 'any' in tmp[5]:
                    worksheet5.write(row, col + 2, "Any")
                    if 'any' in tmp[6]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[6]:
                        worksheet5.write(row, col + 3, tmp[7])
                    elif 'host' in tmp[6]:
                        worksheet5.write(row, col + 3, tmp[7])
                    else:
                        worksheet5.write(row, col + 3, (tmp[6]+" "+tmp[7]))
                elif ('object' or 'object-group') in tmp[5]:
                    worksheet5.write(row, col + 2, tmp[6])
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 4, tmp[9])
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                        #print tmp[10]
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                        #print tmp[10]
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                        worksheet5.write(row, col + 4, tmp[10])
                        #print tmp[10]
                elif 'host' in tmp[5]:
                    worksheet5.write(row, col + 2, tmp[6])
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 4, tmp[9])
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                        #print tmp[10]
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                        worksheet5.write(row, col + 4, tmp[10])
                        #print tmp[10]
                else:
                    worksheet5.write(row, col + 2, (tmp[5]+" "+tmp[6]))
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                        worksheet5.write(row, col + 4, tmp[10])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))
                        worksheet5.write(row, col + 4, tmp[10])

                if 'icmp' in tmp[4]:
                    worksheet5.write(row, col + 4, "ICMP")
                else:
                    worksheet5.write(row, col + 4, "Any")
                
            elif ('object' or 'object-group') in tmp[4]:
                worksheet5.write(row, col + 4, tmp[5])
                if 'any' in tmp[6]:
                    worksheet5.write(row, col + 2, "Any")
                    if 'any' in tmp[7]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[8])
                    else:
                        worksheet5.write(row, col + 3, (tmp[7]+" "+tmp[8]))

                elif ('object' or 'object-group') in tmp[6]:
                    worksheet5.write(row, col + 2, tmp[7])
                    if 'any' in tmp[8]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[8]:
                        worksheet5.write(row, col + 3, tmp[9])
                    elif 'host' in tmp[8]:
                        worksheet5.write(row, col + 3, tmp[9])
                    else:
                        worksheet5.write(row, col + 3, (tmp[8]+" "+tmp[9]))

                elif 'host' in tmp[6]:
                    worksheet5.write(row, col + 2, tmp[7])
                    if 'any' in tmp[8]:
                        worksheet5.write(row, col + 4, tmp[9])
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[8]:
                        worksheet5.write(row, col + 3, tmp[9])
                    elif 'host' in tmp[8]:
                        worksheet5.write(row, col + 3, tmp[9])
                        #print tmp[10]
                    else:
                        worksheet5.write(row, col + 3, (tmp[9]+" "+tmp[10]))
                        #print tmp[10]

                else:
                    worksheet5.write(row, col + 2, (tmp[6]+" "+tmp[7]))
                    if 'any' in tmp[8]:
                        worksheet5.write(row, col + 3, "Any")
                    elif ('object' or 'object-group') in tmp[8]:
                        worksheet5.write(row, col + 3, tmp[9])
                    elif 'host' in tmp[7]:
                        worksheet5.write(row, col + 3, tmp[9])
                    else:
                        worksheet5.write(row, col + 3, (tmp[8]+" "+tmp[9]))

            worksheet5.write(row, col + 1, tmp[1])
            row += 1
            
    print ("Extracting Access List Configuration : Completed")

##########################################
#                                        #
#   Extracting Interface Configuration   #
#                                        #
##########################################

    worksheet6 = workbook.add_worksheet('Interface Configuration')
    row = 0
    col = 0

    worksheet6.write(row, col + 1, "Interface Name")
    worksheet6.write(row, col + 2, "Interface Type")
    worksheet6.write(row, col + 3, "IP Address")
    worksheet6.write(row, col + 4, "Subnet Mask")
    worksheet6.write(row, col + 5, "Standby IP")
    worksheet6.write(row, col + 6, "Security Level")
    worksheet6.write(row, col + 7, "Remark")
    
    row += 1

    for parents in p.find_objects(r"^interface"):
        tmp = parents.text
        #print (tmp)
        worksheet6.write(row, col + 1, tmp.replace("interface", "").lstrip())

        if parents.re_search_children("no ip address"):
            #print (" ip address none")
            worksheet6.write(row, col + 3, "None")
        elif parents.re_search_children("ip address"):           
            for child in p.find_children_w_parents("^%s$" % tmp, 'ip address', ignore_ws=True):
                addrs = child.split()
                ipaddress = addrs[2]
                netmask = addrs[3]
#                VirtualIP = addrs[5]
                
                worksheet6.write(row, col + 3, ipaddress)
                worksheet6.write(row, col + 4, netmask)
#                worksheet6.write(row, col + 5, VirtualIP)

        if parents.re_search_children("nameif"):
             for child in p.find_children_w_parents(tmp, "nameif"):
                nameif = child.replace("nameif", "").lstrip()
                worksheet6.write(row, col + 2, nameif)

        if parents.re_search_children("no security-level"):
            worksheet6.write(row, col + 6, "None")
        elif parents.re_search_children("security-level"):
             for child in p.find_children_w_parents(tmp, "security-level"):
                worksheet6.write(row, col + 6, child.replace("security-level", "").lstrip())
                                
        row += 1
    print ("Extracting Interface Configuration : Completed")
 
    workbook.close()
    print ("All Task Completed")
    print ("Please find your xlsx file in folder")
                # Set the policy name
                child_policy = intobj.re_match_iter_typed(SERVICEPOLICY_RE, result_type=str)
            # Remove the class-default class from the list - it's not useful to us
            class_maps_t.remove (" class class-default")
            # Remove everything but the class-map name from the list
            class_maps = [re.sub(r'^ class ','',s) for s in class_maps_t]
            for class_map_f in class_maps:
                #  Go through the class-maps (that came from the policy-map) and find their config - CiscoConfParse outputs a list so we need add the list string to our new list class_map_p
                class_map_t1 = parse.find_objects (r"^class-map match-a.. " + class_map_f)
                class_map_p.append(class_map_t1[0])
            # Do a list comprehension to search the children of all the class-maps for the ENHANCED-DATA ACL use    
            access_list = [obj for obj in class_map_p if obj.re_search_children(r"match access-group name ENHANCED-DATA") ]
	    if access_list:
                # Write out which class-map uses ENHANCED-DATA
		matching_class_map = access_list[0].re_match(CLASS_MAP_RE)
                access_list_process = parse.find_children_w_parents(r"ip access-list extended ENHANCED-DATA",r"remark Version")
                if access_list_process:
                    access_list_version = re.sub(r'^ remark ','',access_list_process[0])
                else:
                    access_list_version = "No Version Number" 
	    else:
                # If we don't see it, write that out
		matching_class_map = "NO ENHANCED-DATA"
                access_list_version = "No Version Number"
            # Write out to the update file with what we found
            qos_output = (switch + "," + hostname + "," + intobj.re_match(INTERFACE_RE) + "," + policy_map_parent + "," + child_policy + "," + matching_class_map + "," + access_list_version +  "\n")
            f_run.write(qos_output)
	else:
            # Write out when don't find QoS
            qos_output = (switch + "," + hostname + ",No QoS" + "\n")
            f_run.write(qos_output)
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
 def testValues_find_children_w_parents(self):
     ## test find_children_w_parents
     for config, args, result_correct in self.find_children_w_parents_Values:
         cfg = CiscoConfParse(config )
         test_result = cfg.find_children_w_parents(**args)
         self.assertEqual(result_correct, test_result)
print ("Routed Interfaces from config file: %s" % str(sys.argv[1]))


raw_input("Press Return to continue to IP Section...")

ipint = config.find_interface_objects("^interface")
lipint = len(ipint)
for i in ipint:
    print i

print ("Number of items in list: %s" % lipint)
print ("IPs from config file: %s" % str(sys.argv[1]))

raw_input("Press Return to continue to Other IP Section...")

ipint2 = config.find_children_w_parents("^interface\s","ip address")
lipint2 = len(ipint2)
print ipint2
for i in ipint2:
    print i

print ("Number of items in list: %s" % lipint2)
print ("IPs from config file: %s" % str(sys.argv[1]))

raw_input("Press Return to continue to static routes...")

sroute = config.find_objects(r"^ip\sroute")
lsroute = len(sroute)
print sroute
for r in sroute:
    print r
Exemple #9
0
static_routes = list()
prefixlist_entries = list()

DMZ_interface_objs = parse.find_objects_w_child(parentspec='^interface',childspec='vrf member DMZ')
for obj in DMZ_interface_objs:
    interface_ip_raw = obj.re_match_iter_typed(ADDR_RE, result_type=IPv4Obj)
    interface_network = str(interface_ip_raw.network) + '/' + str(interface_ip_raw.prefixlen)
    directly_connected.append(interface_network)

# vrf_objs = parse.find_objects('^vrf context DMZ')
# for obj in vrf_objs:
#    print (obj.ioscfg)
#    static_raw = obj.re_match_iter_typed(STATIC_RE)
#    print(static_raw)

DMZ_static_list = parse.find_children_w_parents('^vrf context DMZ',STATIC_RE)
for x in DMZ_static_list:
    static_rawlist = x.split()
    static_net = static_rawlist[2]
    static_dst = static_rawlist[3]
    #static_net = IPNetwork(static_raw)
    static_routes.append(str(static_net)+' '+str(static_dst))

DMZ_prefix_list = parse.find_lines('^ip prefix-list DMZ_STATIC.*permit.*')
for y in DMZ_prefix_list:
    prefixlist_rawlist = y.split()
    prefixlist_entry = prefixlist_rawlist[6]
    prefixlist_entries.append(prefixlist_entry)


print("Directly Connected Interface Networks in VRF DMZ")
def build_output_files(switch_map, interface_map, input_dir, output_dir,
                       template):
    all_vlans = {
        '1': 'vlan-1-name',
        '2': 'vlan-2-name',
        '3': 'vlan-3-name',
        '4': 'vlan-4-name',
        '6': 'vlan-6-name',
        '8': 'vlan-8-name',
        '10': 'vlan-10-name',
        '12': 'vlan-12-name',
        '14': 'vlan-14-name',
        '16': 'vlan-16-name',
        '18': 'vlan-18-name',
        '20': 'vlan-20-name',
        '22': 'vlan-22-name',
        '23': 'vlan-23-name',
        '24': 'vlan-24-name',
        '25': 'vlan-25-name',
        '26': 'vlan-26-name',
        '28': 'vlan-28-name',
        '30': 'vlan-30-name',
        '32': 'vlan-32-name',
        '34': 'vlan-34-name',
        '36': 'vlan-36-name',
        '38': 'vlan-38-name',
        '40': 'vlan-40-name',
        '44': 'vlan-44-name',
        '50': 'vlan-50-name',
        '52': 'vlan-52-name',
        '54': 'vlan-54-name',
        '58': 'vlan-58-name',
        '60': 'vlan-60-name',
        '62': 'vlan-62-name',
        '64': 'vlan-64-name',
        '66': 'vlan-66-name',
        '70': 'vlan-70-name',
        '74': 'vlan-74-name',
        '76': 'vlan-76-name',
        '80': 'vlan-80-name',
        '90': 'vlan-90-name',
        '96': 'vlan-96-name',
        '100': 'vlan-100-name',
        '102': 'vlan-102-name',
        '103': 'vlan-103-name',
        '104': 'vlan-104-name',
        '106': 'vlan-106-name',
        '108': 'vlan-108-name',
        '110': 'vlan-110-name',
        '198': 'vlan-198-name',
        '201': 'vlan-201-name',
        '202': 'vlan-202-name',
        '203': 'vlan-203-name',
        '204': 'vlan-204-name',
        '205': 'vlan-205-name',
        '208': 'vlan-208-name',
        '214': 'vlan-214-name',
        '221': 'vlan-221-name',
        '224': 'vlan-224-name',
        '250': 'vlan-250-name',
        '305': 'vlan-305-name',
        '307': 'vlan-307-name',
        '317': 'vlan-317-name',
        '330': 'vlan-330-name',
        '342': 'vlan-342-name',
        '502': 'vlan-502-name',
        '505': 'vlan-505-name',
        '506': 'vlan-506-name',
        '666': 'vlan-666-name',
        '990': 'vlan-990-name',
        '996': 'vlan-996-name',
        '997': 'vlan-997-name',
        '998': 'vlan-998-name',
        '999': 'vlan-999-name',
        '1000': 'vlan-1000-name',
        '1002': 'vlan-1002-name',
        '1003': 'vlan-1003-name',
        '1004': 'vlan-1004-name',
        '1005': 'vlan-1005-name',
        '2000': 'vlan-2000-name',
        '2001': 'vlan-2001-name',
        '2002': 'vlan-2002-name'
    }

    switch_interface_map = {}
    switch_vlan_map = {}
    switch_stack_map = {}
    output_switches = []
    last_octet = 160
    for k, v in switch_map.items():
        # Make sure that our output switch exists in out output switches variable
        if v not in output_switches:
            output_switches.append(v)

        # Open our source configuration file and parse the configuration for future use
        s = open(input_dir + k + ".txt", 'r')
        raw_config = s.readlines()
        parsed_config = CiscoConfParse(raw_config)
        s.close()

        # Build interface configuration for new switches and store in variable.

        # Loop for every source/destination port mapping in our source switch
        for source_port, dest_port in interface_map[k].items():
            # Pull the parsed configuration for the current specific source port
            config = parsed_config.find_children_w_parents(
                "^interface " + source_port + "(\r|\n)*$", '.*')
            # Make sure our desination list exists for all output variables
            if v not in switch_interface_map.keys():
                switch_interface_map[v] = []
            if v not in switch_vlan_map.keys():
                switch_vlan_map[v] = []
            if v not in switch_stack_map.keys():
                switch_stack_map[v] = []
            if dest_port.split('/')[0][len(dest_port.split('/')[0]) -
                                       1] not in switch_stack_map[v]:
                switch_stack_map[v].append(
                    dest_port.split('/')[0][len(dest_port.split('/')[0]) - 1])
            # Add our interface line semi-manually
            switch_interface_map[v].append("interface " + dest_port + "\r\n")
            # Iterate through our parsed configuration and add relevant configurations to our list
            for line in config:
                if re.match(
                        "^ (switchport|speed|duplex|description|channel-group).*",
                        line):
                    switch_interface_map[v].append(line)
                    match = re.match("^ switchport.*vlan ([0-9]*).*", line)
                    if match:
                        if match.group(1) not in switch_vlan_map[v]:
                            switch_vlan_map[v].append(match.group(1))

    ## We Start Building Here
    t = open(template, 'r')
    template_config = t.readlines()
    t.close()

    for switch in output_switches:
        d = open(output_dir + switch + ".txt", 'a')
        for template_line in template_config:
            if re.match("^<<< Hostname >>>", template_line):
                d.write("hostname " + switch + "\r\n")
            elif re.match("^<<< Provision Switches >>>", template_line):
                for member in sorted(switch_stack_map[switch]):
                    d.write("switch " + member +
                            " provision ws-c2960x-48lps-l\r\n")
            elif re.match("^<<< Required VLANS >>>", template_line):
                for vlan in sorted(switch_vlan_map[switch], key=int):
                    d.write("Vlan " + vlan + "\r\n")
                    if vlan in all_vlans.keys() and vlan != "1":
                        d.write(" name " + all_vlans[vlan] + "\r\n")
            elif re.match("^<<< Interface Configurations >>>", template_line):
                for int_output in switch_interface_map[switch]:
                    d.write(int_output)
            elif re.match("^<<< Management Interface >>>", template_line):
                d.write("interface Vlan1\r\n")
                d.write(" ip address 172.20.250." + str(last_octet) +
                        " 255.255.255.0\r\n no shut\r\n")
                last_octet += 1
            elif re.match("^snmp-server chassis-id <<< Hostname >>>",
                          template_line):
                d.write("snmp-server chassis-id " + switch + "\r\n")
            else:
                d.write(template_line)
        d.close()
Exemple #11
0
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()