def Modify_Conf():
    parse = CiscoConfParse('cat.txt')

    #特定のI/FのVLAN番号を変更する
    #例:10、12番ポートのVLAN番号を変更する
    for i in range(25):
        if (i == 10):
            for intf in parse.find_objects(r'^interface GigabitEthernet0/' +
                                           str(i)):
                if (intf.has_child_with(r' switchport access vlan')):
                    intf.delete_children_matching(r' switchport access vlan')
                    parse.insert_after(r'^interface GigabitEthernet0/' +
                                       str(i),
                                       insertstr=' switchport access vlan 999',
                                       exactmatch=False,
                                       ignore_ws=False,
                                       atomic=False)
                    parse.commit()

        elif (i == 12):
            for intf in parse.find_objects(r'^interface GigabitEthernet0/' +
                                           str(i)):
                if (intf.has_child_with(r' switchport access vlan')):
                    intf.delete_children_matching(r' switchport access vlan')
                    parse.insert_after(r'^interface GigabitEthernet0/' +
                                       str(i),
                                       insertstr=' switchport access vlan 999',
                                       exactmatch=False,
                                       ignore_ws=False,
                                       atomic=False)
                    parse.commit()

    #新規ファイルに書き込み
    parse.save_as('cat2.txt')
Exemple #2
0
def parse_config(host, addr):
    # search mgmt interface in .txt files
    # interface GigabitEthernet3 is MGMT interface
    txt_cfg = lab_folder + host + ".txt"
    mgmt_interface = "GigabitEthernet3"
    ip_param = "ip address " + addr + " 255.255.255.0"

    parse = CiscoConfParse(txt_cfg, factory=True)
    interface = parse.find_interface_objects(mgmt_interface)
    # add interface gig3

    if interface == []:
        print("creating mgmt interface")
        parse.insert_before('line con 0', 'interface GigabitEthernet3')
        parse.commit()

        for obj in parse.find_interface_objects(mgmt_interface):
            obj.append_to_family('!')
            obj.append_to_family(' no shutdown')
            obj.append_to_family(' ' + ip_param)
            obj.append_to_family(' description MGMT')

        parse.commit()
        parse.save_as(txt_cfg)
    else:
        print("Interface already configured")
        pass
def Audit():
    ## Parse the config
    parse = CiscoConfParse('conf.txt')

    for i in range(25):
        ## Add a new switchport at the bottom of the config...
        parse.append_line('interface FastEthernet0/' + str(i))
        parse.append_line(' switchport')
        parse.append_line(' switchport mode access')
        parse.append_line('!')
        parse.commit()  # commit() **must** be called before searching again

    ## Search and standardize the interfaces...
    standardize_intfs(parse)
    parse.commit()  # commit() **must** be called before searching again

    ## I'm illustrating regular expression usage in has_line_with()
    if not parse.has_line_with(r'^service\stimestamp'):
        ## prepend_line() adds a line at the top of the configuration
        parse.prepend_line(
            'service timestamps debug datetime msec localtime show-timezone')
        parse.prepend_line(
            'service timestamps log datetime msec localtime show-timezone')

    ## Write the new configuration
    parse.save_as('conf3.txt')
Exemple #4
0
    def convert_vrf(ios_conf_file, new_conf_file, vrf_name):
        xr_conf = CiscoConfParse(new_conf_file)
        vrf_attrib = IosVrfConfigParser.ios_get_vrf_attrib(
            ios_conf_file, vrf_name)

        if vrf_attrib['VRF_NAME']:
            print "create vrf config"
            xr_conf.append_line("vrf " + vrf_attrib['VRF_NAME'])
            xr_conf.append_line(" address-family ipv4 unicast")

        if vrf_attrib['EX_MAP']:
            print "create EXPORT Route-policy"
            for ex_map in vrf_attrib['EX_MAP']:
                xr_conf.append_line(" export route-policy " + ex_map)

        if vrf_attrib['IM_MAP']:
            print "create IMPORT Route-policy"
            for im_map in vrf_attrib['IM_MAP']:
                xr_conf.append_line(" export route-policy " + im_map)

        if vrf_attrib['RT_EXPORT']:
            print "create Export Route-Target "
            for rt_export in vrf_attrib['RT_EXPORT']:
                xr_conf.append_line(" export route-target " + rt_export)

        if vrf_attrib['RT_IMPORT']:
            print "create Import Route-Target "
            for rt_import in vrf_attrib['RT_IMPORT']:
                xr_conf.append_line(" export route-target " + rt_import)
        xr_conf.commit()
        xr_conf.save_as(new_conf_file)
        ## Add missing commands
        if is_switchport_access and (not has_stormcontrol):
            intf.append_to_family(' storm-control action trap')
            intf.append_to_family(' storm-control broadcast level 0.4 0.3')

        ## remove dot1q trunk misconfiguration
        elif is_switchport_trunk:
            intf.delete_children_matching('port-security')

## Parse the config
parse = CiscoConfParse('switch.conf')

## Add a new switchport at the bottom of the config...
parse.append_line('interface GigabitEthernet1/0')
parse.append_line(' switchport')
parse.append_line(' switchport mode access')
parse.append_line('!')
parse.commit ()

## Search and standardize the interfaces
standardize_interfaces(parse)
parse.commit()

## Add a line to the top of the config if not already there.
if not parse.has_line_with(r'^service\stimestamp'):
    parse.prepend_line('service timestamps debug datetime msec localtime show-timezone')
    parse.prepend_line('service timestamps log datetime msec localtime show-timezone')

## Wrtite the config file now...
parse.save_as('switch.conf.new')
    SWversion = parse.re_match_iter_typed(r'^version\s(\S+)',
                                          default='no version')
    #print('SW Version: ' + SWversion)

    # Iterate over all the interface objects
    for intf_obj in parse.find_objects('^interface'):

        has_switchport_access = intf_obj.has_child_with(
            r'switchport mode access')
        has_shutdown = intf_obj.has_child_with(r'shutdown')
        has_netdescript = intf_obj.has_child_with(
            r'description.*(router|switch|uplink|circuit).*')

        if (has_switchport_access or has_shutdown) and not has_netdescript:
            interfaces.append(intf_obj.text)
            intf_obj.append_to_family(
                ' description **This Port Has Been NAC Enabled**')
            outFile.write(intf_obj.text)
            outFile.write(
                '\n description **This Port Has Been NAC Enabled**\n')
        #else:
        #print(intf_obj.text + ' did not meet critera and won\'t be modified')

    #Print interfaces which meet the child critera - for debugging
    print(*interfaces, sep=', ')
    #Close the new configuration file that only contains NAC additions
    outFile.close()
    #Write new file that contains complete config, including old and new lines
    parse.save_as(changes + '/' + filename + '.new')
Exemple #7
0
            primary_config.append_line(" standby 1 ip %s secondary" % ipv4_address.ip)

        primary_config.append_line(" standby 1 priority 255")
        primary_config.append_line(" standby 1 authentication md5 key-string vl%s" % vlan_id)
        primary_config.append_line("!")

        secondary_config.append_line("interface %s" % vlan_interface_string)
        secondary_config.append_line(" description *** VLAN SVI %s" % vlan_id)
        secondary_config.append_line(" ip address %s %s" % (secondary_ip, ipv4_addr.netmask))
        for ipv4_address in add_ip_addresses:
            # determine secondary IP address
            if IPv4Address(ipv4_address.ip + 2) in ipv4_address.network.hosts():
                secondary_ip = ipv4_address + 2
            else:
                secondary_ip = ipv4_address - 2
            secondary_config.append_line(" ip address %s %s secondary" % (secondary_ip.ip, ipv4_address.netmask))

        secondary_config.append_line(" standby version 2")
        secondary_config.append_line(" standby 1 ip %s" % virtual_ip)
        for ipv4_address in add_ip_addresses:
            secondary_config.append_line(" standby 1 ip %s secondary" % ipv4_address.ip)

        secondary_config.append_line(" standby 1 priority 254")
        secondary_config.append_line(" standby 1 authentication md5 key-string vl%s" % vlan_id)
        secondary_config.append_line("!")

    # write results
    print("Write results...")
    primary_config.save_as(os.path.join(output_directory, primary_configuration_file))
    secondary_config.save_as(os.path.join(output_directory, secondary_configuration_file))
        intf.append_to_family(
            ' authentication event server dead action authorize voice')
        intf.append_to_family(' authentication host-mode multi-auth')
        intf.append_to_family(' switchport mode access')
        intf.append_to_family(' authentication open')
        intf.append_to_family(' authentication order dot1x mab')
        intf.append_to_family(' authentication priority mab dot1x')
        intf.append_to_family(' authentication port-control auto')
        intf.append_to_family(' authentication periodic')
        intf.append_to_family(' authentication timer reauthenticate server')
        intf.append_to_family(' mab')
        intf.append_to_family(' dot1x pae authenticator')
        intf.append_to_family(' dot1x timeout tx-period 3')

## Write the new configuration and save it as a file in a path of your choosing.
parse.save_as(filename)

driver = get_network_driver('ios')
iosvl2 = driver(IP,
                username,
                password,
                optional_args={'global_delay_factor': 2})
iosvl2.open()

print("Accessing" + device)
iosvl2.load_merge_candidate(filename=filename)

#if the config in the txt document is not present in the switch the config file will be added to the switch and then saved.
#ip scp server enable needs to be added to the switch for this to work

diffs = iosvl2.compare_config()
Exemple #9
0
        has_stormcontrol = intf.has_child_with(r' storm-control broadcast')
        is_switchport_access = intf.has_child_with(r'switchport mode access')
        is_switchport_trunk = intf.has_child_with(r'switchport mode trunk')

        ## Add missing features
        if is_switchport_access and (not has_stormcontrol):
            intf.append_to_family(' storm-control action trap')
            intf.append_to_family(' storm-control broadcast level 0.4 0.3')

        ## Remove dot1q trunk misconfiguration...
        elif is_switchport_trunk:
            intf.delete_children_matching('port-security')
            intf.delete_children_matching('nonegotiate') #cust request 1

## Parse the configs
parse = CiscoConfParse('ios_audit.conf') # this is our input file

## Search and standardize the interfaces...
standardize_intfs(parse)
parse.commit()     # commit() **must** be called before searching again

## regular expression usage in has_line_with() to find if the config has a matching line 
if not parse.has_line_with(r'^service\stimestamp'):
    ## prepend_line() adds a line at the top of the configuration
    parse.prepend_line('service timestamps debug datetime msec localtime show-timezone')
    parse.prepend_line('service timestamps log datetime msec localtime show-timezone')
    parse.prepend_line('this config was hacked by Robert')
## Write the new configuration
#customization request: make it output to .conf.new2
parse.save_as('ios_audit.conf.new2')
Exemple #10
0
            intf.append_to_family(' storm-control broadcast level 0.4 0.3')

        ## remove dot1q trunk misconfiguration
        elif is_switchport_trunk:
            intf.delete_children_matching('port-security')


## Parse the config
parse = CiscoConfParse('switch.conf')

## Add a new switchport at the bottom of the config...
parse.append_line('interface GigabitEthernet1/0')
parse.append_line(' switchport')
parse.append_line(' switchport mode access')
parse.append_line('!')
parse.commit()

## Search and standardize the interfaces
standardize_interfaces(parse)
parse.commit()

## Add a line to the top of the config if not already there.
if not parse.has_line_with(r'^service\stimestamp'):
    parse.prepend_line(
        'service timestamps debug datetime msec localtime show-timezone')
    parse.prepend_line(
        'service timestamps log datetime msec localtime show-timezone')

## Wrtite the config file now...
parse.save_as('switch.conf.new')
Exemple #11
0
    parse.delete_lines(r'loop-detection')
    parse.delete_lines(r'errdisable recovery cause loop-detect')
    parse.delete_lines(r'errdisable recovery cause all')

    ## Cleans up vlan configuraiton.
    vlans = [
        ('11', wifi_vlans),
        ('22', voice_vlan),
        ('24', facilitys_vlan),
        ('42', data_vlan),
        ('56', wifi_vlans)
    ]
    tagged_ports = lambda vlan: parse.replace_children(
        r'vlan\s+{0}'.format(vlan[0]), r'!', 'tagged ' + ' '.join([port_name(port) for port in sorted(vlan[1])])
    )
    port_name = lambda port: ' '.join([port.text[10:11], port.text[19:]])
    parse.replace_all_children(r'vlan.*', r'[un]?tagged.*', '!')
    for x in vlans: tagged_ports(x)
    # parse.replace_all_children(r'vlan.*', r'REPLACE', '')


## Parse the config
parse = CiscoConfParse('brocade_conf.cfg')

## Search and standardize the configuration
standardize_intfs(parse)
parse.commit()  # commit() **must** be called before searching again

## Write the new configuration
parse.save_as('brocade_conf.cfg.new')
for intf in parse.find_objects(r'^interface.+?thernet'):
    vlan_id = intf.re_match_iter_typed(r'switchport access vlan (\S+)',
                                       default='')

    #If the interface is a switchport access without the dot1x it will be selected to have the below configuration added.
    is_switchport_access = intf.has_child_with(r'switchport access vlan')
    is_switchport_mode_trunk = intf.has_child_with(r'switchport mode trunk')
    #This is the config that will be applied to each of the selected interfaces with the variable vlan_id from the loop command from above.
    if is_switchport_access and (not is_switchport_mode_trunk):
        intf.append_to_family(
            ' device-tracking attach-policy ISE-DEVICE-TRACK-POL')
        intf.append_to_family(
            ' authentication event server dead action authorize vlan ' +
            vlan_id)
        intf.append_to_family(
            ' authentication event server dead action authorize voice')
        intf.append_to_family(' authentication host-mode multi-auth')
        intf.append_to_family(' switchport mode access')
        intf.append_to_family(' authentication open')
        intf.append_to_family(' authentication order dot1x mab')
        intf.append_to_family(' authentication priority dot1x mab')
        intf.append_to_family(' authentication port-control auto')
        intf.append_to_family(' authentication periodic')
        intf.append_to_family(' authentication timer reauthenticate server')
        intf.append_to_family(' mab')
        intf.append_to_family(' dot1x pae authenticator')
        intf.append_to_family(' dot1x timeout tx-period 3')

## Write the new configuration and save it as a file in a path of your choosing.
parse.save_as('h:/Scripts/Cisco_Python/newswitchconfig.txt')
def convert_cfg_file(config, device_type, out_path, conversion_matrix):
    """Convert cfg file to other cfg file"""

    import os
    import re
    from ciscoconfparse import CiscoConfParse

    # Check if device type exist in conversion matrix
    if device_type in conversion_matrix:
        # Determine new filename
        new_filename = os.path.join(out_path, os.path.basename(config))
        if os.path.isfile(new_filename):  # Remove CFG if it exist
            os.remove(new_filename)

        # Parse cisco configuration with Ciscoconfparse
        parse = CiscoConfParse(config)

        # DELETE
        for item in conversion_matrix[device_type]["delete"]:
            if item[1] == None:  # Check required fields
                continue
            elif item[0] != None:  # Parent cmd is mentionned
                parent_object = parse.find_objects(item[0])
                for parent in parent_object:
                    # Delete child object in parent object
                    parent.delete_children_matching(item[1])
            else:  # parent cmd is not mentionned
                cli_objects = parse.find_objects(item[1])
                for cli_object in cli_objects:
                    # Delete object and all child objects if exist
                    cli_object.delete()

        # ADD
        for item in conversion_matrix[device_type]["add"]:
            if item[2] == None:  # Check required fields
                continue
            elif item[0] != None:  # parent cmd is mentionned
                parent_object = parse.find_objects(item[0])
                parent_object_done = list(
                )  # This is to avoid duplicate added entries
                for parent in parent_object:
                    parent_re = re.compile(parent.text)
                    if parent.has_children == True:  # Add space to child if they are child
                        if parent.text not in parent_object_done:  # Avoid duplicates entries
                            nb_space = len(parent.text) - len(
                                parent.text.lstrip()) + 1
                            parse.insert_after(parent_re,
                                               insertstr=" " * nb_space +
                                               item[2])
                            parent_object_done.append(parent.text)
                    else:  # Entry is at the root of cfg, no space added
                        parse.insert_after(parent_re, insertstr=item[2])
            else:  # parent cmd is not mentionned
                parse.append_line(item[2])  # Write line at the end of the file

        # REPLACE
        for item in conversion_matrix[device_type]["replace"]:
            if item[1] == None or item[2] == None:  # Check required fields
                continue
            if item[0] != None:  # parent cmd is mentionned
                initial_cmd = re.compile(item[1])
                parse.replace_children(item[0], initial_cmd, item[2])
            else:  # parent cmd is not mentionned
                initial_cmd = re.compile(item[1])
                parse.replace_lines(initial_cmd, item[2])

        # Write output to out_file
        parse.save_as(new_filename)
    else:
        new_filename = "Skipped (model unknown)"

    return new_filename
        arp_ipv4_addr = IPv4Address(ipv4)

        # assign static arp entry to the VLAN SVI interface
        for vlan_svi in vlan_svis:
            svi_ipv4_network = IPv4Network(vlan_svi['ipv4_addr'] + "/" +
                                           vlan_svi['ipv4_netmask'],
                                           strict=False)
            if arp_ipv4_addr in svi_ipv4_network.hosts():
                # extend the model if the correct IP network is found
                if "static_arps" not in vlan_svi.keys():
                    vlan_svi['static_arps'] = list()
                record = {'ipv4_host': ipv4, 'mac': mac}
                vlan_svi['static_arps'].append(record)

                # a static ARP is only defined on a single interface
                break

    print("Write results to file...")
    cisco_nxos_template = CiscoConfParse(['!'])

    for vlan_svi in vlan_svis:
        cisco_nxos_template.append_line("interface Vlan%s" %
                                        vlan_svi['vlan_id'])
        for static_arp in vlan_svi['static_arps']:
            cisco_nxos_template.append_line(
                " ip arp %s %s" % (static_arp['ipv4_host'], static_arp['mac']))
        cisco_nxos_template.append_line('!')

    cisco_nxos_template.save_as(
        os.path.join(output_dir, "cisco_nxos_config.txt"))
Exemple #15
0
        ## Remove dot1q trunk misconfiguration...
        elif is_switchport_trunk:
            intf.delete_children_matching('port-security')


## Parse the config
parse = CiscoConfParse('short.conf')

## Add a new switchport at the bottom of the config...
parse.append_line('interface FastEthernet0/4')
parse.append_line(' switchport')
parse.append_line(' switchport mode access')
parse.append_line('!')
parse.commit()  # commit() **must** be called before searching again

## Search and standardize the interfaces...
standardize_intfs(parse)
parse.commit()  # commit() **must** be called before searching again

## I'm illustrating regular expression usage in has_line_with()
if not parse.has_line_with(r'^service\stimestamp'):
    ## prepend_line() adds a line at the top of the configuration
    parse.prepend_line(
        'service timestamps debug datetime msec localtime show-timezone')
    parse.prepend_line(
        'service timestamps log datetime msec localtime show-timezone')

## Write the new configuration
parse.save_as('short.conf.new')
def transform(filename):

	#1st Part

	with open(os.path.join(app.config['UPLOAD_FOLDER'],filename), "rU") as infile:

		p = CiscoConfParse(infile)

		objs = list()

		objs.extend(p.find_objects(r'^policy-map'))
		objs.extend(p.find_objects(r'ip\saccess-list'))
		objs.extend(p.find_objects(r'^class-map'))
		objs.extend(p.find_objects(r'^crypto pki'))
		objs.extend(p.find_objects(r'^track'))
		objs.extend(p.find_objects(r'^ip sla'))
		objs.extend(p.find_objects(r'^zone-pair'))
		objs.extend(p.find_objects(r'^archive'))
		objs.extend(p.find_objects(r'^banner '))
		objs.extend(p.find_objects(r'^line '))
		objs.extend(p.find_objects(r'^username'))
		objs.extend(p.find_objects(r'^logging '))
		objs.extend(p.find_objects(r'^end'))
		objs.extend(p.find_objects(r'^access-list'))

		for obj in objs:
			obj.delete()

		for interface in p.find_objects_w_child('^interface', 'spanning-tree portfast'):
			interface.delete(interface)

		for interface in p.find_objects_w_child('^interface', 'switchport port-security'):
			interface.delete(interface)

		p.commit()

		p.save_as (os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_1st.txt'))


	#2nd Part

	with open (os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_1st.txt'), "rU") as file_parsed_2nd:

		with open(os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_2nd.txt'), "w") as outfile:

			security_lines = ['last','Last','version','service timestamps','service password','tcp-keepalives','marker','flow-','enable secret',
							'csdb', 'ip accouting','timezone','aaa','ssh','snmp','service-policy','tacacs','privilege',
							'alias','ntp','scheduler allocate','exec-timeout', 'service pad','syslog',
							'small-servers','enable password','zone-member','zone security','ip http','mls','igmp', 'radius-server',
							'forward-protocol','cdp','nagle','resource policy','gratuitous-arps','resource policy''control-plane',
							'-time','errdisable','#','Building configuration','Current configuration','memory-size iomem','no ip source-route',
							'no ip bootp server','no ip domain lookup','no ipv6 cef','no logging console','multilink bundle-name authenticated',
							'ip accounting','standby']

			emptyline = ['\n', '\r\n']

			for line in file_parsed_2nd:
				if not line in emptyline and not any(security_line in line for security_line in security_lines):
					outfile.write(line)



	# 3rd Part

			outfile.write('enable secret cisco\n')
			outfile.write('line vty 0 4\n')
			outfile.write('    password cisco\n')
			outfile.write('    no access-class 23 in\n')
			outfile.write('end\n')
			outfile.write('!\n')



		return send_file(os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_2nd.txt'))
        for intf in parse.find_objects(r'^interface.+?thernet'):
            vlan_id = intf.re_match_iter_typed(r'switchport access vlan (\S+)',
                                               default='')

            #If the interface is a switchport access without the dot1x it will be selected to have the below configuration added.
            is_switchport_access = intf.has_child_with(
                r'switchport access vlan')
            is_switchport_trunk = intf.has_child_with(r'switchport mode trunk')
            #This is the config that will be applied to each of the selected interfaces with the variable vlan_id from the loop command from above.
            if is_switchport_access and (not is_switchport_trunk):
                intf.append_to_family(
                    ' authentication event server dead action authorize vlan '
                    + vlan_id)
                intf.append_to_family(
                    ' authentication event server dead action authorize voice')
                intf.append_to_family(' authentication host-mode multi-auth')
                intf.append_to_family(' switchport mode access')
                intf.append_to_family(' authentication open')
                intf.append_to_family(' authentication order dot1x mab')
                intf.append_to_family(' authentication priority mab dot1x')
                intf.append_to_family(' authentication port-control auto')
                intf.append_to_family(' authentication periodic')
                intf.append_to_family(
                    ' authentication timer reauthenticate server')
                intf.append_to_family(' mab')
                intf.append_to_family(' dot1x pae authenticator')
                intf.append_to_family(' dot1x timeout tx-period 3')

## Write the new configuration and save it as a file in a path of your choosing.
        parse.save_as('H:\Scripts\Cisco_Python\sw_' + device + '.txt')
def transform(filename):

    #1st Part

    with open(os.path.join(app.config['UPLOAD_FOLDER'], filename),
              "rU") as infile:

        p = CiscoConfParse(infile)

        objs = list()

        objs.extend(p.find_objects(r'^policy-map'))
        objs.extend(p.find_objects(r'ip\saccess-list'))
        objs.extend(p.find_objects(r'^class-map'))
        objs.extend(p.find_objects(r'^crypto pki'))
        objs.extend(p.find_objects(r'^track'))
        objs.extend(p.find_objects(r'^ip sla'))
        objs.extend(p.find_objects(r'^zone-pair'))
        objs.extend(p.find_objects(r'^archive'))
        objs.extend(p.find_objects(r'^banner '))
        objs.extend(p.find_objects(r'^line '))
        objs.extend(p.find_objects(r'^username'))
        objs.extend(p.find_objects(r'^logging '))
        objs.extend(p.find_objects(r'^end'))
        objs.extend(p.find_objects(r'^access-list'))

        for obj in objs:
            obj.delete()

        for interface in p.find_objects_w_child('^interface',
                                                'spanning-tree portfast'):
            interface.delete(interface)

        for interface in p.find_objects_w_child('^interface',
                                                'switchport port-security'):
            interface.delete(interface)

        p.commit()

        p.save_as(
            os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_1st.txt'))

    #2nd Part

    with open(os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_1st.txt'),
              "rU") as file_parsed_2nd:

        with open(
                os.path.join(app.config['UPLOAD_FOLDER'],
                             'file_parsed_2nd.txt'), "w") as outfile:

            security_lines = [
                'last', 'Last', 'version', 'service timestamps',
                'service password', 'tcp-keepalives', 'marker', 'flow-',
                'enable secret', 'csdb', 'ip accouting', 'timezone', 'aaa',
                'ssh', 'snmp', 'service-policy', 'tacacs', 'privilege',
                'alias', 'ntp', 'scheduler allocate', 'exec-timeout',
                'service pad', 'syslog', 'small-servers', 'enable password',
                'zone-member', 'zone security', 'ip http', 'mls', 'igmp',
                'radius-server', 'forward-protocol', 'cdp', 'nagle',
                'resource policy', 'gratuitous-arps', 'resource policy'
                'control-plane', '-time', 'errdisable', '#',
                'Building configuration', 'Current configuration',
                'memory-size iomem', 'no ip source-route',
                'no ip bootp server', 'no ip domain lookup', 'no ipv6 cef',
                'no logging console', 'multilink bundle-name authenticated',
                'ip accounting', 'standby'
            ]

            emptyline = ['\n', '\r\n']

            for line in file_parsed_2nd:
                if not line in emptyline and not any(
                        security_line in line
                        for security_line in security_lines):
                    outfile.write(line)

    # 3rd Part

            outfile.write('enable secret cisco\n')
            outfile.write('line vty 0 4\n')
            outfile.write('    password cisco\n')
            outfile.write('    no access-class 23 in\n')
            outfile.write('end\n')
            outfile.write('!\n')

        return send_file(
            os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_2nd.txt'))
Exemple #19
0
rg = re.compile(re1, re.IGNORECASE | re.DOTALL)
l2agg = rg.search(text)

if l2agg:
    for intf in parse.find_objects(r'^interface.+?thernet'):
        has_qos_trust = intf.has_child_with(r' mls qos trust dscp')
        is_switchport_trunk = intf.has_child_with(r'switchport mode trunk')
        is_switchport_infra = intf.has_child_with(r'INFRA:TRUNK*.*')

        if (is_switchport_trunk
                and is_switchport_infra) and (not has_qos_trust):
            cfgdiff.append_line("!")
            cfgdiff.append_line(intf.text)
            cfgdiff.append_line("mls qos trust dscp")
    cfgdiff.save_as(config_file + '_new')
    print("Config Created with _new extension for L2AGG")
else:
    for intf in parse.find_objects(r'^interface.+?thernet'):
        has_qos_trust = intf.has_child_with(r' mls qos trust dscp')
        is_switchport_trunk = intf.has_child_with(r'switchport mode trunk')
        is_switchport_infra = intf.has_child_with(r'INFRA:TRUNK*.*')
        is_switchport_access = intf.has_child_with(r'switchport mode access')
        is_switchport_shutdown = intf.has_child_with(r'shutdown')

        if (is_switchport_trunk
                and is_switchport_infra) and (not has_qos_trust):
            cfgdiff.append_line("!")
            cfgdiff.append_line(intf.text)
            cfgdiff.append_line("mls qos trust dscp")
        elif (is_switchport_access and
        # now we create an IP address object from the ARP entry
        arp_ipv4_addr = IPv4Address(ipv4)

        # assign static arp entry to the VLAN SVI interface
        for vlan_svi in vlan_svis:
            svi_ipv4_network = IPv4Network(vlan_svi['ipv4_addr'] + "/" + vlan_svi['ipv4_netmask'], strict=False)
            if arp_ipv4_addr in svi_ipv4_network.hosts():
                # extend the model if the correct IP network is found
                if "static_arps" not in vlan_svi.keys():
                    vlan_svi['static_arps'] = list()
                record = {
                    'ipv4_host': ipv4,
                    'mac': mac
                }
                vlan_svi['static_arps'].append(record)

                # a static ARP is only defined on a single interface
                break

    print("Write results to file...")
    cisco_nxos_template = CiscoConfParse(['!'])

    for vlan_svi in vlan_svis:
        cisco_nxos_template.append_line("interface Vlan%s" % vlan_svi['vlan_id'])
        for static_arp in vlan_svi['static_arps']:
            cisco_nxos_template.append_line(" ip arp %s %s" % (static_arp['ipv4_host'], static_arp['mac']))
        cisco_nxos_template.append_line('!')

    cisco_nxos_template.save_as(os.path.join(output_dir, "cisco_nxos_config.txt"))
Exemple #21
0
# 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')
        if (ipv4_addr.ip_object + 1) in ipv4_network.hosts():
            primary_ip = ipv4_addr.ip_object + 1
            secondary_ip = ipv4_addr.ip_object + 2
        else:
            primary_ip = ipv4_addr.ip_object - 1
            secondary_ip = ipv4_addr.ip_object - 2

        # now add the configuration to the change scripts
        primary_config.append_line("interface %s" % vlan_interface_string)
        primary_config.append_line(" description *** VLAN SVI %s" % vlan_id)
        primary_config.append_line(" ip address %s %s" % (primary_ip, ipv4_addr.netmask))
        primary_config.append_line(" standby version 2")
        primary_config.append_line(" standby 1 ip %s" % virtual_ip)
        primary_config.append_line(" standby 1 priority 255")
        primary_config.append_line(" standby 1 authentication md5 key-string vl%s" % vlan_id)
        primary_config.append_line("!")

        secondary_config.append_line("interface %s" % vlan_interface_string)
        secondary_config.append_line(" description *** VLAN SVI %s" % vlan_id)
        secondary_config.append_line(" ip address %s %s" % (secondary_ip, ipv4_addr.netmask))
        secondary_config.append_line(" standby version 2")
        secondary_config.append_line(" standby 1 ip %s" % virtual_ip)
        secondary_config.append_line(" standby 1 priority 254")
        secondary_config.append_line(" standby 1 authentication md5 key-string vl%s" % vlan_id)
        secondary_config.append_line("!")

    # write results
    print("Write results...")
    primary_config.save_as(os.path.join(output_directory, primary_configuration_file))
    secondary_config.save_as(os.path.join(output_directory, secondary_configuration_file))
Exemple #23
0
        original_config.write(out)
        original_config.close()
        parse = CiscoConfParse(original_config_filename)

        # Add required configuration under interface configuration (reading new commands from file)

        for intf in parse.find_objects(r'^interface.+?thernet'):
            is_access_vlan_users = intf.has_child_with(
                r'switchport access vlan ' + str(vlan))
            if is_access_vlan_users:
                for cmd in commands_list:
                    intf.append_to_family(" " + str(cmd))

        ## save the new configuration in file

        new_config_filename = "new_config" + "_" + ip_address_of_device
        parse.save_as(new_config_filename)

        ## delete unnecessary lines 'Building configuration' 'size' ..

        lines = open(new_config_filename).readlines()
        open(new_config_filename, 'w').writelines(lines[3:-1])

        ## open the new configuration file and push it to device

        with open(new_config_filename) as n:
            cfg_commands = n.read().splitlines()
            output = net_connect.send_config_set(cfg_commands)
            net_connect.disconnect()
            print(output)
Exemple #24
0
re1='(ag)'

rg = re.compile(re1,re.IGNORECASE|re.DOTALL)
l2agg = rg.search(text)

if l2agg:
    for intf in parse.find_objects(r'^interface.+?thernet'):
        has_qos_trust = intf.has_child_with(r' mls qos trust dscp')
        is_switchport_trunk = intf.has_child_with(r'switchport mode trunk')
        is_switchport_infra = intf.has_child_with(r'INFRA:TRUNK*.*')

        if (is_switchport_trunk and is_switchport_infra) and (not has_qos_trust):
            cfgdiff.append_line("!")
            cfgdiff.append_line(intf.text)
            cfgdiff.append_line("mls qos trust dscp")
    cfgdiff.save_as(config_file+'_new')
    print ("Config Created with _new extension for L2AGG")
else:
    for intf in parse.find_objects(r'^interface.+?thernet'):
        has_qos_trust = intf.has_child_with(r' mls qos trust dscp')
        is_switchport_trunk = intf.has_child_with(r'switchport mode trunk')
        is_switchport_infra = intf.has_child_with(r'INFRA:TRUNK*.*')
        is_switchport_access = intf.has_child_with(r'switchport mode access')
        is_switchport_shutdown = intf.has_child_with(r'shutdown')

        if (is_switchport_trunk and is_switchport_infra) and (not has_qos_trust):
            cfgdiff.append_line("!")
            cfgdiff.append_line(intf.text)
            cfgdiff.append_line("mls qos trust dscp")
        elif (is_switchport_access and (not is_switchport_shutdown)) and (not has_qos_trust):
            cfgdiff.append_line("!")