Exemple #1
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)
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 #3
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 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')
def testValues_banner_delete_01():
    # Ensure multiline banners are correctly deleted
    CONFIG = [
        '!', 'banner motd ^', '    trivial banner1 here ^',
        'interface GigabitEthernet0/0', ' ip address 192.0.2.1 255.255.255.0',
        'banner exec ^', '    trivial banner2 here ^', 'end'
    ]
    parse = CiscoConfParse(CONFIG)
    for obj in parse.find_objects('^banner'):
        obj.delete()
    parse.commit()
    assert parse.find_objects('^banner') == []
def testValues_banner_delete_01():
    # Ensure multiline banners are correctly deleted
    CONFIG = ['!', 
        'banner motd ^', '    trivial banner1 here ^', 
        'interface GigabitEthernet0/0',
        ' ip address 192.0.2.1 255.255.255.0',
        'banner exec ^', '    trivial banner2 here ^',
        'end']
    parse = CiscoConfParse(CONFIG)
    for obj in parse.find_objects('^banner'):
        obj.delete()
    parse.commit()
    assert parse.find_objects('^banner')==[]
def testValues_aaa_authfailmsg_delete_01():
    # Ensure  aa authentication fail-message banners are correctly deleted
    CONFIG = ['!', 
        'aaa authentication fail-message ^', 
        '    trivial banner1 here ^', 
        'interface GigabitEthernet0/0',
        ' ip address 192.0.2.1 255.255.255.0',
        'banner exec ^', '    trivial banner2 here ^',
        'end']
    parse = CiscoConfParse(CONFIG)
    for obj in parse.find_objects('^aaa\sauthentication\sfail-message'):
        obj.delete()
    parse.commit()
    assert parse.find_objects('^aaa\sauthentication\sfail-message')==[]
def remove_config_blocks(run_config):

    parse = CiscoConfParse(run_config)
    # delete exiting configuration that needs to be replaced
    for obj in parse.find_objects(r"^interface"):
        obj.delete()
    for obj in parse.find_objects(r"boot system"):
        obj.delete()

    # commit modifications to the current parse object
    parse.commit()

    #return IOS formated config to be used in script

    return '\n'.join(parse.ioscfg)
    # use below parse command if file needs to be saved locally
    # parse.save_as('modified_startup')
def testValues_banner_delete_02():
    # Ensure multiline banners are correctly deleted
    #
    # Check for Github issue #37
    CONFIG = [
        '!', 'interface GigabitEthernet0/0',
        ' ip address 192.0.2.1 255.255.255.0', 'banner motd ^',
        '    trivial banner1 here ^', 'interface GigabitEthernet0/1',
        ' ip address 192.0.2.1 255.255.255.0', 'banner exec ^',
        '    trivial banner2 here ^', 'end'
    ]
    parse = CiscoConfParse(CONFIG)
    for obj in parse.find_objects('^banner'):
        obj.delete()
    parse.commit()

    assert parse.find_objects('^banner') == []

    # Github issue #37 assigned Gi0/1's child to Gi0/0 after deleting
    #  the banner motd line...
    for obj in parse.find_objects('^interface'):
        assert len(obj.children) == 1
def testValues_banner_delete_02():
    # Ensure multiline banners are correctly deleted
    #
    # Check for Github issue #37
    CONFIG = ['!', 
        'interface GigabitEthernet0/0',
        ' ip address 192.0.2.1 255.255.255.0',
        'banner motd ^', '    trivial banner1 here ^', 
        'interface GigabitEthernet0/1',
        ' ip address 192.0.2.1 255.255.255.0',
        'banner exec ^', '    trivial banner2 here ^',
        'end']
    parse = CiscoConfParse(CONFIG)
    for obj in parse.find_objects('^banner'):
        obj.delete()
    parse.commit()

    assert parse.find_objects('^banner')==[]

    # Github issue #37 assigned Gi0/1's child to Gi0/0 after deleting
    #  the banner motd line...
    for obj in parse.find_objects('^interface'):
        assert len(obj.children)==1
Exemple #11
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')
Exemple #12
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 #13
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')
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'))
        ## 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')
Exemple #16
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')
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'))