Exemple #1
0
def process_file(fname):
    with open(fname) as f:
        print '*** %s ***' % fname
        parse = CiscoConfParse(f)
        blockhead = parse.find_blocks('voice translation')

        for item in blockhead:
            print item.rstrip()
Exemple #2
0
def process_file(fname):
    with open(fname) as f:
        print '*** %s ***' % fname
        parse = CiscoConfParse(f)
        blockhead = parse.find_blocks('voice translation')

        for item in blockhead:
            print item.rstrip()
Exemple #3
0
def findEthPort(socket, *last_config):
    '''
    parse Cisco config and return interfaces list
    '''
    # extract from tupel -> list
    last_config = last_config[0]
    ports = []
    # run
    for path in last_config:
        parse = CiscoConfParse(path)
        switch = path.split("/")
        serial_objs = parse.find_blocks("description "+socket)
        if serial_objs:
            ports.append('<h4>Switch: ' + switch[3] + '</h4>')
        for obj in serial_objs:
            ports.append(obj)
        serial_objs = []
    return ports
def asa_to_mx(arg_file):
    # Read port_mappings.csv file for name/number pairs, such as (www, 80)
    # https://www.cisco.com/c/en/us/td/docs/security/asa/asa82/configuration/guide/config/ref_ports.html#wp1007738
    port_mappings = dict()
    csv_file = open('port_mappings.csv')
    reader = csv.reader(csv_file, delimiter=',', quotechar='"')
    next(reader, None)
    for row in reader:
        [name, tcpudp, number, description] = row
        port_mappings[name] = number

    # Set the CSV output file and write the header row
    #timenow = '{:%Y%m%d_%H%M%S}'.format(datetime.now())
    #filename = 'mx_l3fw_rules_{0}.csv'.format(timenow)
    filename = 'mx_l3fw_rules_{0}.csv'.format(arg_file)
    output_file = open(filename, mode='w', newline='\n')
    field_names = [
        'policy', 'protocol', 'srcCidr', 'srcPort', 'destCidr', 'destPort',
        'comment', 'logging'
    ]
    csv_writer = csv.DictWriter(output_file,
                                delimiter=',',
                                quotechar='"',
                                quoting=csv.QUOTE_ALL,
                                fieldnames=field_names)
    csv_writer.writeheader()

    # Open "sh run" output file and parse
    with open(arg_file, 'U') as f:
        newText = f.read()
        while more_line_text in newText:
            newText = newText.replace(more_line_text, '')
    with open('asa_to_mx_scrubbed.txt', 'w') as f:
        f.write(newText)

    parse = CiscoConfParse('asa_to_mx_scrubbed.txt', syntax='asa')

    print("...scrubbed config")
    # Parse out name objects for ASA v 7
    network_mappings = {}
    name_objects = parse.find_objects(r'name ')
    for element in name_objects:
        name = element.text
        if name[:5] != 'name ':
            continue
        name = name.replace('name ', '').split()
        network_mappings[name[1]] = name[0] + '/32'
    print("...looked up names for asa V7")

    print("...parsing network interfaces...")
    network_interfaces = {}
    int_objects = parse.find_objects(r'Port-channel1.')
    for element in int_objects:
        lines = element.children
        intName = element.text
        text = find_interfaces(intName, lines, network_interfaces)

    print(network_interfaces)
    #exit()

    #parse "object network"
    solo_objects = parse.find_objects(r'object network')
    for element in solo_objects:
        name = element.text.replace('object network ', '')
        lines = element.children
        text = asa_to_mx_l3(lines, solo_objects)
        network_mappings[name] = text

    print(".. Solo objects parsed")

    # Parse "object-group network" blocks in lines 143-441
    network_objects = parse.find_objects(r'object-group network')
    for element in network_objects:
        name = element.text.replace('object-group network ', '')
        lines = element.children
        print(lines)
        text = asa_to_mx_l3(lines, network_mappings)
        network_mappings[name] = text

    print("parsed object-groups network")
    # Parse "object-group service" blocks, in lines 442-571
    # Add to loaded port_mappings from file
    service_objects = parse.find_objects(r'object-group service')
    for element in service_objects:
        name = element.text.replace('object-group service ', '')
        name = name.split()[0]
        lines = element.children
        text = asa_to_mx_l4(lines, port_mappings)
        port_mappings[name] = text
    print("parsed object-group service")

    # Default deny rule, to be added at very end
    network_mappings['any'] = 'Any'
    default_deny = False

    f = open("networkmappings_raw.txt", "w+")
    f.write(str(network_mappings))
    f.close()
    p = open("portmappings_raw.txt", "w+")
    p.write(str(port_mappings))
    p.close()

    print("Checking ACL lists to parse...")
    # Open acl_list.txt, which determines which extended ACLs to parse
    acl_list = open('acl_list.txt')
    for acl_line in acl_list:
        acl_name = acl_line.strip()
        acl_block = parse.find_blocks(r'access-list {0}'.format(acl_name))
        for command in acl_block:
            rule = {}
            line = command.strip()
            #line = line.split('extended ')[1]
            line = line.replace('extended', '')
            line = line.split(acl_name)[1]
            # finished edits
            command = line
            fields = line.split()
            # Remove irrelevant terms
            fields = [
                x for x in fields
                if x not in ('eq', 'object-group', 'echo-reply', 'unreachable',
                             'time-exceeded', 'object')
            ]
            policy = fields.pop(0)
            if policy == 'permit':
                rule['policy'] = 'allow'
            elif policy == 'deny':
                rule['policy'] = 'deny'
            elif policy == 'remark':
                #print("Remark found and ignored")
                continue
            else:
                print("error(ACL): allow/deny")
                print(fields)
                sys.exit(command)

            protocol = fields.pop(0)
            if protocol == 'ip':
                rule['protocol'] = 'any'
            elif protocol == 'TCPUDP':
                rule['protocol'] = 'any'
            elif protocol == 'icmp':
                rule['protocol'] = 'icmp'
            elif protocol == 'udp':
                rule['protocol'] = 'udp'
            elif protocol == 'tcp':
                rule['protocol'] = 'tcp'
            else:
                print("error(ACL): protocol expected [" + protocol + "]")
                print(str(fields))
                if protocol in port_mappings:
                    print("YUP its a PORT range")
                    print(port_mappings[protocol])
                    #rule['protocol'] = 'any'
                    rule['destPort'] = port_mappings[protocol]
                    print(str(rule))
                    #exit()
                else:
                    print("Unknown protocol")
                    exit()
                #fields.insert(0,protocol)

            srcCidr = fields.pop(0)
            if srcCidr == "any4": srcCidr = "any"

            if srcCidr in network_mappings:
                rule['srcCidr'] = network_mappings[srcCidr]
            elif isIP(srcCidr) and isIP(fields[0]):
                #  print("ADDY:" + srcCidr +"/"+ fields[0])
                ip = ipaddress.ip_interface('{0}/{1}'.format(
                    srcCidr, nm_bits(fields[0])))
                newSrc = ip.with_prefixlen
                if isIP(newSrc):
                    next_field = fields.pop(0)  #burn one off, for netmask
                    #                    next_field = fields.pop(0) #burn one off, for netmask

                    rule['srcCidr'] = newSrc
                else:
                    print("Horrific srcDest=" + newDest)
                    print("Command:" + command)
                    print("error(NextField)342:" + next_field)
                    print(str(fields))
                    print(str(rule))
                    exit()
            elif srcCidr == "host" and isIP(fields[0]):
                rule['srcCidr'] = fields[0] + "/32"
                next_field = fields.pop(0)
#                next_field = fields.pop(0)
#                print(rule['srcCidr'])
#                print(next_field)
#                sys.exit(command)

            next_field = fields.pop(0)

            #  rule['srcPort'] = 'any' #cheater line
            if next_field in port_mappings:
                if next_field == 'any':
                    rule['srcPort'] = 'Any'
                else:
                    rule['srcPort'] = port_mappings[next_field]
                next_field = fields.pop(0)
            elif next_field in network_mappings:
                rule['srcPort'] = 'Any'  #HERE
                rule['destCidr'] = network_mappings[next_field]
                if len(fields) > 0: next_field = fields.pop(0)
            elif next_field == 'host':
                rule['srcPort'] = 'Any'
                next_field = fields.pop(0)
                if isIP(next_field):
                    rule['destCidr'] = next_field + "/32"
                    if len(fields) > 0: next_field = fields.pop(0)
                else:
                    print("error(ACL): insane error")
                    exit()
            elif next_field.isdigit():
                if int(next_field) < 65535 and int(next_field) > 0:
                    rule['srcPort'] = next_field
                    next_field = fields.pop(0)

        ### this should be destination

            if len(fields) > 1 and isIP(next_field) and isIP(fields[0]):

                ip = ipaddress.ip_interface('{0}/{1}'.format(
                    next_field, nm_bits(fields[0])))
                newDest = ip.with_prefixlen
                if isIP(newDest):
                    rule['destCidr'] = newDest
                    next_field = fields.pop(0)  #pull off the mask
                    next_field = fields.pop(0)  #pull off the mask

#                    if len(fields) > 0: next_field = fields.pop(0) #queue the next one
# else:
#    sys.exit("UNKNOWN")

                else:
                    print("Horrific newDest=" + newDest)
                    print("Command:" + command)
                    print("error(NextField)DST:" + next_field)
                    print(str(fields))
                    print(str(rule))
                    sys.exit(command)

            else:
                if 0 == 1:
                    #am i dropping anything here?
                    print("Command:" + command)
                    print("warning(NextField)?!?:" + next_field)
                    print(str(fields))
                    print(str(rule))
                    #sys.exit(command)

            #next_field = fields.pop(0)

            rule['destPort'] = ''
            if len(fields) == 0:
                if not 'destCidr' in rule: rule['destCidr'] = 'Any'
                rule['destPort'] = 'Any'
            elif next_field == 'any' or next_field == 'any4':
                if not 'destCidr' in rule: rule['destCidr'] = 'Any'
                next_field = fields.pop(0)
            elif next_field in port_mappings:
                rule['destPort'] = port_mappings[next_field]
            elif len(fields) == 1:

                if next_field.isnumeric():
                    rule['destPort'] = next_field
                elif next_field == "log":
                    if rule['destPort'] == '': rule['destPort'] = 'Any'
                elif not isIP(next_field) and next_field in port_mappings:
                    rule['destPort'] = port_mappings[next_field]
                else:
                    print("Command:" + command)
                    print("error(NextField):" + next_field)
                    print(str(fields))
                    print(str(rule))

#                    sys.exit("ERROR!!@#!@$@!$")

            if next_field == "any4" or next_field == "any":
                rule['destCidr'] = 'Any'
                if len(fields) > 0: next_field = fields.pop(0)

            elif next_field in network_mappings:
                #could be a group of device IPs
                print("status(ACL): Network Object detected [" +
                      str(next_field) + "]")
                rule['srcPort'] = 'Any'
                rule['destCidr'] = network_mappings[next_field]
                rule['destPort'] = 'Any'
            elif len(fields) > 0 and isIP(next_field) and isIP(
                    fields[0]) and nm_bits(fields[0]) >= 8:
                #so basically use case of a "10.0.0.0 255.0.0.0 " host
                #print("warning(ACL): seperate source & mask "+str(next_field)+"/"+str(fields[0]))
                rule['srcPort'] = 'Any'
                rule['destCidr'] = next_field + "/" + str(nm_bits(fields[0]))
                rule['destPort'] = 'Any'
#                print(rule['destCidr'])
            elif next_field.isdigit():
                print("NextField: " + str(next_field))
                if int(next_field) < 65535 and int(next_field) > 0:
                    rule['destPort'] = next_field
                else:
                    print("err(ACL): is digit, not in range")
                    print("fields: " + str(fields))
                    sys.exit(command)
            elif next_field in port_mappings:
                rule['destPort'] = port_mappings[next_field]

            else:
                #ANYTHING landing here should be fixed

                print("warning(ACL): keyword[" + next_field + "]")
                print("fields: " + str(fields))
                print(next_field)
                print(rule)
#                sys.exit(command)

            if next_field == "range":
                if fields[0] in port_mappings or fields[1] in port_mappings:
                    print("error(ACL): Named Object in range")
                    sys.exit("BARF")
                else:
                    print("we're good")

                rule['destPort'] = fields[0] + '-' + fields[1]
                #                rule['destPort'] = enumerate_ports(fields[0] + "-" + fields[1]) #adding a fix here to solve for range "135-netbios"

                next_field = fields.pop(0)
                next_field = fields.pop(0)
                if len(fields) > 0: next_field = fields.pop(0)

            #cheater function (looks for empty fields and sets to any)
            if len(fields) > 0 and rule['destPort'] == "":
                next_field = fields.pop(0)
                print('')
                if next_field == "log":
                    if rule['destPort'] == "": rule['destPort'] = 'Any'
                elif next_field.isdigit():
                    rule['destPort'] = next_field
                elif next_field == "range":
                    port_range = (fields[0] + "-" + fields[1])
                    #                    rule['destPort'] = enumerate_ports(port_range)
                    rule['destPort'] = port_range

                elif next_field in port_mappings:
                    rule['destPort'] = port_mappings[next_field]
                else:
                    print("error(emptyField): No DestPort")
                    print("Current Command: " + next_field)
                    print("Fields:" + str(fields))
                    print("RULES:" + str(rule))
                    print("Commands:" + str(command))
                    sys.exit(command)
            elif rule['destPort'] == "":
                rule['destPort'] = "Any"

            for r in rule:
                if len(rule[r]) < 2:
                    print("error(Fields): Empty field")
                    print("RULES:" + str(rule))
                    print("Commands:" + str(command))
                    sys.exit(command)
            if not 'destCidr' in rule:
                print(rule)
                print("error(end): No destCIDR, something went terribly wrong")
                sys.exit(command)
            if not 'protocol' in rule:
                rule['protocol'] = 'Any'
            if not 'srcPort' in rule:
                print(rule)
                print("error(end): No sourcePort ")
                rule['srcPort'] = 'Any'

            print("******")
            print("Command:" + command)
            print(str(fields))
            print("FinalRule: " + str(rule))
            print("******")

            if rule == {
                    'policy': 'deny',
                    'protocol': 'any',
                    'srcCidr': 'Any',
                    'srcPort': 'Any',
                    'destCidr': 'Any',
                    'destPort': 'Any'
            }:
                default_deny = True
                continue

            rule['comment'] = command
            rule['logging'] = SYSLOG_ENABLED
            csv_writer.writerow(rule)

    if default_deny:
        csv_writer.writerow({
            'policy': 'deny',
            'protocol': 'any',
            'srcCidr': 'Any',
            'srcPort': 'Any',
            'destCidr': 'Any',
            'destPort': 'Any',
            'comment': 'Default deny ip any any',
            'logging': SYSLOG_ENABLED
        })

    output_file.close()
    print('Output CSV written to file {0}'.format(filename))
Exemple #5
0
def parse(filename, subdir):
    parse = CiscoConfParse('configurations/' + subdir + '/' +
                           filename)  # Load in source configuration file
    output_config = {}  # Create master dict for output data

    # switch stacks
    stacks = parse.find_objects(r'switch [0-9]+ provision (.*)')
    if stacks:
        output_config['switch_stack'] = []
        for line in stacks:
            stack = line.re_match(r'switch [0-9]+ provision (.*)')
            output_config['switch_stack'].append(stack)

    # Interfaces
    interfaces = parse.find_objects(r'interface')  # Create interfaces object
    if interfaces:
        output_config['interfaces'] = []  # Create list of interfaces
        for interface in interfaces:
            # dict for this particular interface
            interface_dict = {}

            # Insert interface name
            interface_name = interface.re_match(r'^interface (\S+)$')
            if interface_name:
                interface_dict['name'] = interface_name

            # switchport

            # Find list of interfaces with "switchport" config
            switchport_interfaces = interface.re_search_children(r'switchport')
            if switchport_interfaces:

                # Create switchport dict if it does not yet exist
                if not 'switchport' in interface_dict:
                    interface_dict['switchport'] = {}

                for line in switchport_interfaces:

                    # access vlan
                    access_vlan = line.re_match(
                        r' switchport access vlan (\S+)')
                    if access_vlan:
                        interface_dict['switchport'][
                            'access_vlan'] = access_vlan

                    # switchport mode
                    switchport_mode = line.re_match(
                        r'^ switchport mode (\S+)$')
                    if switchport_mode:
                        interface_dict['switchport']['mode'] = switchport_mode

                    # port-security
                    port_sec = line.re_search(r'^ switchport port-security$')
                    if port_sec:
                        interface_dict['switchport']['port_security'] = True

                    # switchport trunk
                    switchport_trunk = line.re_search(r'^ switchport trunk.*$')
                    if switchport_trunk:

                        # Create the trunk dict if it does not yet exist
                        if not 'trunk' in interface_dict['switchport']:
                            interface_dict['switchport']['trunk'] = {}

                        # native vlan
                        native_vlan = line.re_match(
                            r'^ switchport trunk native vlan (\S+)$')
                        if native_vlan:
                            interface_dict['switchport']['trunk'][
                                'native_vlan'] = native_vlan

                        # allowed vlan
                        allowed_vlan = line.re_match(
                            r'^ switchport trunk allowed vlan (\S+)$')
                        if allowed_vlan:
                            interface_dict['switchport']['trunk'][
                                'allowed_vlan'] = allowed_vlan

                        # trunk encapsulation
                        encapsulation = line.re_match(
                            r'^ switchport trunk encapsulation (.+)$')
                        if encapsulation:
                            interface_dict['switchport']['trunk'][
                                'encapsulation'] = encapsulation

            # spanning-tree
            spanning_tree = interface.re_search_children(r'spanning-tree')
            if spanning_tree:
                # Create spanning-tree dict if it does not yet exist
                if not 'spanning_tree' in interface_dict:
                    interface_dict['spanning_tree'] = {}

                for line in spanning_tree:

                    # portfast
                    portfast = line.re_search(r'^ spanning-tree portfast$')
                    if portfast:
                        interface_dict['spanning_tree']['portfast'] = True

                    # guard_root
                    guard_root = line.re_search(r'^ spanning-tree guard root$')
                    if guard_root:
                        interface_dict['spanning_tree']['guard_root'] = True

            # ip
            ip = interface.re_search_children(r'^ ip ')
            if ip:
                # Create ip dict if it does not yet exist
                if not 'ip' in interface_dict:
                    interface_dict['ip'] = {}

                for line in ip:
                    # ip address
                    ip_address = line.re_match(r'^ ip address (.*)$')
                    if ip_address:
                        interface_dict['ip']['address'] = ip_address

                    # ip access_group
                    access_group = re.match('^ ip access-group (\S+) (\S+)$',
                                            line.text)
                    if access_group:
                        # Create access_group sub-dict if it does not yet exist
                        if not 'access_group' in interface_dict['ip']:
                            interface_dict['ip']['access_group'] = {}

                        interface_dict['ip']['access_group'][
                            access_group.group(1)] = access_group.group(2)

                    # ip dhcp snooping trust
                    dhcp_snooping_trust = line.re_search(
                        r'^ ip dhcp snooping trust$')
                    if dhcp_snooping_trust:
                        interface_dict['ip']['dhcp_snooping_trust'] = True

            # no ip
            no_ip = interface.re_search_children(r'^ no ip ')

            if no_ip:
                # Create ip dict if it does not yet exist
                if not 'ip' in interface_dict:
                    interface_dict['ip'] = {}

                for line in no_ip:

                    # no ip address
                    no_ip = line.re_search(r'^ no ip address$')
                    if no_ip:
                        interface_dict['ip']['ip_address_disable'] = True

                    # no ip route cache
                    no_route_cache = line.re_search(r'^ no ip route-cache$')
                    if no_route_cache:
                        interface_dict['ip']['route_cache_disable'] = True

                    # no ip mroute-cache
                    no_mroute_cache = line.re_search(r'^ no ip mroute-cache$')
                    if no_mroute_cache:
                        interface_dict['ip']['mroute_cache_disable'] = True

            # ipv6
            ipv6 = interface.re_search_children(r'^ ipv6 ')
            if ipv6:
                if not 'ipv6' in interface_dict:
                    interface_dict['ipv6'] = []

                for line in ipv6:
                    # ra guard
                    ra_guard = line.re_search(r'^ ipv6 nd raguard$')
                    if ra_guard:
                        interface_dict['ipv6'].append('ra_guard')

                    # ipv6 snooping
                    ra_guard = line.re_search(r'^ ipv6 snooping$')
                    if ra_guard:
                        interface_dict['ipv6'].append('ipv6_snooping')

                    # ipv6 dhcp guard
                    ra_guard = line.re_search(r'^ ipv6 dhcp guard$')
                    if ra_guard:
                        interface_dict['ipv6'].append('ipv6_dhcp_guard')

            # misc
            misc = interface.re_search_children(r'.*')

            if misc:
                for line in misc:

                    # description
                    interface_description = line.re_match(
                        r'^ description (\S+)$')
                    if interface_description:
                        interface_dict['description'] = interface_description

                    # power inline police
                    power_inline_police = line.re_search(
                        r'^ power inline police$')
                    if power_inline_police:
                        interface_dict['power_inline_police'] = True

                    # cdp disable
                    cdp_disable = line.re_search(r'^ no cdp enable$')
                    if cdp_disable:
                        interface_dict['cdp_disable'] = True

                    # shutdown
                    shutdown = line.re_search(r'^ shutdown$')
                    if shutdown:
                        interface_dict['shutdown'] = True

                    # vrf forwarding
                    vrf = line.re_match(r'^ vrf forwarding (.+)$')
                    if vrf:
                        interface_dict['vrf'] = vrf

                    # negotiation
                    negotiation = line.re_match(r'^ negotiation (.+)$')
                    if negotiation:
                        interface_dict['negotiation'] = negotiation

                    # keepalive disable
                    keepalive_disable = line.re_search(r'^ no keepalive$')
                    if keepalive_disable:
                        interface_dict['keepalive_disable'] = True

            # Append the completed interface dict to the interfaces list
            output_config['interfaces'].append(interface_dict)

    # IP Config Elements
    ip_config = parse.find_objects(r'ip')
    if ip_config:
        # Create ip dict if it does not yet exist
        if not 'ip' in output_config:
            output_config['ip'] = {}

        for line in ip_config:

            # ip dhcp snooping
            dhcp_snooping = line.re_search(r'^ip dhcp snooping$')
            if dhcp_snooping:
                output_config['ip']['dhcp_snooping'] = True

            # ip default gateway
            default_gateway = line.re_match(r'^ip default-gateway (\S+)$')
            if default_gateway:
                output_config['ip']['default_gateway'] = default_gateway

    # Banner
    banner = parse.find_blocks(r'banner')
    if banner:
        # Create banner dict if it does not yet exist
        if not 'banner' in output_config:
            output_config['banner'] = []

        for line in banner:
            first_line = re.search(r'^banner motd (.*)$', line)
            if first_line:
                output_config['banner'].append(first_line.group(1))
            else:
                output_config['banner'].append(line)

    # acl
    acl = parse.find_blocks(r'access-list')
    if acl:
        if not 'acl' in output_config:
            output_config['acl'] = []

        for line in acl:
            acl_line = re.search(r'^access-list 10 permit (172.*)$', line)
            if acl_line:
                output_config['acl'].append(acl_line.group(1))

    # snmp-server
    snmp = parse.find_blocks(r'snmp-server')
    if snmp:
        # Create snmp dict if it does not yet exist
        if not 'snmp' in output_config:
            output_config['snmp'] = {}

        for line in snmp:

            # community string
            snmp_community = re.match(r'^snmp-server community (\S+)', line)
            if snmp_community:
                output_config['snmp']['community'] = snmp_community.group(1)

            # location
            snmp_location = re.match(r'^snmp-server location (.*)$', line)
            if snmp_location:
                output_config['snmp']['location'] = snmp_location.group(1)

            # contact
            snmp_contact = re.match(r'^snmp-server contact (.*)$', line)
            if snmp_contact:
                output_config['snmp']['contact'] = snmp_contact.group(1)

    # vtp
    vtp = parse.find_lines(r'vtp')
    if vtp:
        vtp_mode = re.match(r'vtp mode (\S+)', vtp[0])
        if vtp_mode:
            output_config['vtp_mode'] = vtp_mode.group(1)

    # vlans
    vlans = parse.find_objects('^vlan [0-9]+')
    if vlans:
        # Create vlans dict if it does not yet exist
        if not 'vlans' in output_config:
            output_config['vlans'] = []

        for vlan in vlans:
            vlan_dict = {}

            # vlan number
            vlan_number = re.match('^vlan ([0-9]+)$', vlan.text)
            if vlan_number:
                vlan_dict['number'] = vlan_number.group(1)

            # vlan name
            vlan_name = vlan.re_search_children(r'name')
            if vlan_name:
                name = vlan_name[0].re_match(r' name (\S+)')
                vlan_dict['name'] = name

            # Append the completed vlan dict
            output_config['vlans'].append(vlan_dict)

    # certificates
    certificate_chain = parse.find_lines('^crypto pki certificate chain')
    if certificate_chain:
        for line in certificate_chain:
            certificate_chain_search = re.match(
                '^crypto pki certificate chain (\S+)', line)
            output_config['crypto_chain_id'] = certificate_chain_search.group(
                1)

    # radius server config
    radius_servers = parse.find_objects('radius server')
    if radius_servers:
        output_config['dot1x'] = True

    # Screen output
    # print
    # print(subdir + '/' + filename + ' YAML Output:')
    # print
    # print yaml.dump(output_config, default_flow_style=False, explicit_start=True)
    print('Outputing ' + filename + ' YAML')

    # Make sure the directory we're trying to write to exists. Create it if it doesn't
    out_path = 'yaml/' + subdir + '/'
    if not exists(out_path):
        makedirs(out_path)

    # Write foo.yml to the subdir in yaml/ that corresponds to the dir where we got the input file in configurations/
    with open(out_path + splitext(filename)[0] + '.nwid.bris.ac.uk.yml',
              'w') as outfile:
        yaml.dump(output_config,
                  outfile,
                  default_flow_style=False,
                  explicit_start=True)
def MainFunc(filelist,filepath,protocol,linstr,outputfolder,label_list):
    mydict,mylist=returnAttributes(protocol,label_list)
    print("-----------------------1")
    print(mydict)
    print("-----------------------2")
    print(mylist)
    mylist3=mylist[:]
    for k,v in mydict.items():
        if '/' in v:
            vv=v.split('/')
            for e in vv:
                if len(e)>0:
                    mylist3.append(e)

    #filelist=os.listdir(filepath)
    for eachfile in filelist:
        if '.DS' in eachfile:
            continue
        with open(ProjectPath+"/"+outputfolder+"/input_"+linstr,"w")as fout:
            pass

    for eachfile in filelist:
        if '.DS' in eachfile:
            continue
        with open(filepath+'/'+eachfile)as fin:
            linsout=[]
            for eachline in fin:
                if "Authentication Data Removed" in eachline or '/*' in eachline:
                    #print(eachline)
                    pass
                else:
                    linsout.append(eachline)
        with open(filepath+'/'+eachfile,"w")as fout:
            fout.writelines(linsout)

        if len(eachfile)>0:
            print(eachfile)
            protocol2=r'[ \t]*'+protocol+'.*$'
            linstr2=r'[\s]*'+linstr+'[\s]*$'
            parse_file = CiscoConfParse(str(filepath+'/'+eachfile))

            #val_block0=parse_file.find_blocks(protocol2,exactmatch=False,ignore_ws=True)
            val_children0=parse_file.find_all_children(protocol2,exactmatch=False,ignore_ws=True)

            val0=val_children0
            #print("val_children000000")
            #print(val_children0)

            if str(linstr)!="input patterns":
                parse0 = CiscoConfParse(val0)
                val_block=parse0.find_blocks(linstr2,exactmatch=False,ignore_ws=True)
                #val_children=parse_file.find_children_w_parents(parentstr,linstr,ignore_ws=True)
                val_children=parse0.find_all_children(linstr2,exactmatch=False,ignore_ws=True)

                print("val_block...")
                print(val_block)
                print('val_children...')
                print(val_children)

                val1=val_block+val_children
            else:
                val1=val_children0
            #val1=val_children
            #print("val1///")
            #print(val1)
            parse1 = CiscoConfParse(val1)

            val2=[]
            for each in mylist:
                #print("each............................."+each)
                each2=r'[\s]*'+each+'[\w\s;\[\]\-\.]+.*'
                temp=parse1.find_all_children(each2,exactmatch=True,ignore_ws=True)
                val2.extend(temp)
            #val=parse.find_all_children('group CONNECTOR',exactmatch=False,ignore_ws=True)
            #print('val2....')
            #print(val2)
            val3=[]
            #print("mylist3........")
            #print(mylist3)
            for each in val2:
                itema=each.replace('{','').replace('#','').strip()+','
                if islistcontainstr(mylist3,each) and not itema in val3:
                    #print("+++++++++++++++++++++++++++++++++++++++++++++++++++++"+each)
                    val3.append(itema)

            Output=[]
            outputtab=0

            for tab in range(len(mylist)):
                Output.append([])
            for k,v in mydict.items():
                matchlist=[]
                if v=="int":
                    pattern=re.compile(r"[\s]*"+k+"[\s]*[\d]+")
                    for each in val3:
                        #print(each)
                        matchlist.extend(pattern.findall(each))
                    #print("222222222222222222222222222")
                    #print(matchlist)
                    #print(val3)
                elif v=="bool":
                    pattern=re.compile(r"[\s]*"+k+'[\s]*')
                    for each in val3:
                        matchlist.extend(pattern.findall(each))
                    #print("111111111111111111111")
                    #print(matchlist)
                else:
                    v=v.replace('/','|').replace('\\','|')
                    pattern=re.compile(r"[\s]*"+k+'[\s]*'+'('+v+')')
                    for each in val3:
                        matchlist.extend(pattern.findall(each))
                    if matchlist:
                        for t in range(len(matchlist)):
                            matchlist[t]=k+' '+matchlist[t]

                if matchlist:
                    print("333333333333333333333")
                    print(matchlist)
                    Output[outputtab].extend(matchlist)
                    if len(matchlist)==1:
                        Output[outputtab].extend(',')
                outputtab += 1
            #print(Output)
            #print(filepath+"/output"+linstr)
            with open(ProjectPath+"/"+outputfolder+"/input_"+linstr,"a")as fout:
                for each in Output:
                    fout.writelines(each)
                fout.write('\n')
Exemple #7
0
#!/usr/bin/python

from ciscoconfparse import CiscoConfParse

parse = CiscoConfParse("conf.txt")
basic_search = parse.find_blocks("trunk")
print basic_search

# 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)
f.close()

# Sanitize he output for [
f = open("output.txt", "r")
filedata = f.read()
f.close()
newdata = filedata.replace("[", "")
Exemple #8
0
#cisco centric scripts for parsing out config-------
#------------------------------------
from ciscoconfparse import CiscoConfParse
parse = CiscoConfParse('vg1.router.txt')
blockhead = parse.find_blocks('voice translation')
for item in blockhead:
    print item
#-------------------------------------