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 #2
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 #3
0
        elif is_switchport_trunk or has_switchport_negotiate:
            #use two if statement to only remove the oone it finds
            if is_switchport_trunk:
                intf.delete_children_matching('port-security')

            if has_switchport_negotiate:
                intf.delete_children_matching('negotiate')


## Parse the config
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')

#Add name to the top of the file
if not parse.has_line_with(r'^config by: '):
    user = argv[1]
    parse.prepend_line('Config by: ' + str(user))

## Write the new configuration
parse.save_as('ios_audit.conf.new2')
        ## 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 #5
0
def main():
    confparse = CiscoConfParse(config.USER_CONFIG)
    cfgdiffs = CiscoConfParse([])

    for template in config.TEMPLATES:
        template_dict = load_template(template)
        template_name = template_dict["TEMPLATE_NAME"]
        template_type = template_dict["TEMPLATE_TYPE"]
        print(f'{Fore.BLUE}VERIFYING TEMPlATE: ' + template_name)
        print(f'**************************************{Style.RESET_ALL}')

        for template_section in template_dict["SECTIONS"]:
            regex_pattern = template_section["SECTION_REGEX"]
            sub_regex_patterns = template_section["LINES"]
            section_name = template_section["NAME"]
        #regex_pattern = template_dict["SECTION_REGEX"]
        #sub_regex_patterns = template_dict["LINES"]

            print(f'{Fore.GREEN}-VERIFYING SECTION: {Fore.CYAN}' + section_name + f'{Style.RESET_ALL}')

            ## Find all matching sections (multi line objects)
            objects = confparse.find_objects(regex_pattern)
            ## Verify first if the whole section is missing
            if len(objects) == 0:
                cfgdiffs.append_line(f'{Fore.RED} -> MISSING WHOLE SECTION:')
                cfgdiffs.append_line(f'{Fore.RED}    ' + regex_pattern)
                for subregex in sub_regex_patterns:
                    cfgdiffs.append_line("        " + subregex)
                    is_valid = False

                if (is_valid == False):
                    for line in cfgdiffs.ioscfg:
                        print(f'{Fore.RED}' + line + f'{Style.RESET_ALL}')
                cfgdiffs = CiscoConfParse([])

            ## If the section is there, verify if some parts are missing
            else:
                for object in objects:
                    is_valid = True

                    ## Mark that some lines are missing if we ever have to print that object
                    cfgdiffs.append_line(f'{Fore.RED} -> MISSING OR DIFFERENTLY CONFIGURED LINES')
                    cfgdiffs.append_line(f'   ' + object.text + f'{Style.RESET_ALL}')

                    ## Search children of the object
                    for subregex in sub_regex_patterns:
                        if not (object.re_search_children(subregex)):
                            cfgdiffs.append_line("    " + subregex)
                            is_valid = False

                    if(is_valid==False):
                        for line in cfgdiffs.ioscfg:
                            print(f'{Fore.RED}' + line + f'{Style.RESET_ALL}')
                    else:
                        print(f'{Fore.GREEN} -> SUCCESS - CONFIG SECTION: ' + template_name + ' FOR OBJECT: ' + object.text + f'{Style.RESET_ALL}')

                    #Reset cfgdiffs for next object
                    cfgdiffs = CiscoConfParse([])

        ## Find all single line objects
        if(template_type=='SINGLE_LINE_AND_MULTI_SECTION'):
            is_valid = True
            print(f'{Fore.GREEN}-VERIFYING GENERAL LINES: {Style.RESET_ALL}')
            regex_patterns = template_dict["SINGLE_LINE_REGEXES"]
            for line in regex_patterns:
                if not confparse.has_line_with(line):
                    print(f'{Fore.RED} -> MISSING OR DIFFERENTLY CONFIGURED LINES: ' + line + f'{Style.RESET_ALL}')
                    is_valid = False
            if (is_valid==True):
                print(f'{Fore.GREEN} -> SUCCESS - GENERAL CONFIG PARTS: ' + template_name + f'{Style.RESET_ALL}')

        print(f'{Fore.BLUE}*****************END*********************{Style.RESET_ALL}\n')
from ciscoconfparse.ccp_util import IPv4Obj

if __name__ == "__main__":
    # the result dictionary
    result = {"features": [], "interfaces": {}}

    # create CiscoConfParse object using a configuration file stored in the
    # same directory as the script
    confparse = CiscoConfParse("example_config.txt")

    # check if OSPF is used as the routing protocol
    # the following regex_pattern matches only the "router ospf <process-id>" command (no VRFs)
    ospf_regex_pattern = r"^router ospf \d+$"

    # in this case, we will simply check that the ospf router command is part of the config
    is_ospf_in_use = confparse.has_line_with(ospf_regex_pattern)

    if is_ospf_in_use:
        print("==> OSPF is used in this configuration")
        result["features"].append("ospf")
    else:
        print("==> OSPF is not used in this configuration")

    # extract the interface name and description
    # first, we get all interface commands from the configuration
    interface_cmds = confparse.find_objects(r"^interface ")

    # iterate over the resulting IOSCfgLine objects
    for interface_cmd in interface_cmds:
        # get the interface name (remove the interface command from the configuration line)
        intf_name = interface_cmd.text[len("interface "):]
    # the result dictionary
    result = {
        "features": [],
        "interfaces": {}
    }

    # create CiscoConfParse object using a configuration file stored in the
    # same directory as the script
    confparse = CiscoConfParse("example_config.txt")

    # check if OSPF is used as the routing protocol
    # the following regex_pattern matches only the "router ospf <process-id>" command (no VRFs)
    ospf_regex_pattern = r"^router ospf \d+$"

    # in this case, we will simply check that the ospf router command is part of the config
    is_ospf_in_use = confparse.has_line_with(ospf_regex_pattern)

    if is_ospf_in_use:
        print("==> OSPF is used in this configuration")
        result["features"].append("ospf")
    else:
        print("==> OSPF is not used in this configuration")

    # extract the interface name and description
    # first, we get all interface commands from the configuration
    interface_cmds = confparse.find_objects(r"^interface ")

    # iterate over the resulting IOSCfgLine objects
    for interface_cmd in interface_cmds:
        # get the interface name (remove the interface command from the configuration line)
        intf_name = interface_cmd.text[len("interface "):]
Exemple #8
0
)

shutdown_intfs = orig_config.find_parents_w_child(parentspec=r"^interface",
                                                  childspec='shutdown')
pprint(shutdown_intfs)

# EX2: Does this configuration has a router

from ciscoconfparse import CiscoConfParse
from pprint import pprint

orig_config = CiscoConfParse(
    "/media/bassim/DATA/GoogleDrive/Packt/EnterpriseAutomationProject/Chapter5_Extract_useful_data_from_network_devices/Cisco_Config.txt"
)

check_router = orig_config.has_line_with(r"^router")
pprint(check_router)

# --
from ciscoconfparse import CiscoConfParse

orig_config = CiscoConfParse(
    "/media/bassim/DATA/GoogleDrive/Packt/EnterpriseAutomationProject/Chapter5_Extract_useful_data_from_network_devices/Cisco_Config.txt"
)
print orig_config.has_line_with("^aaa new-model")

# EX3: Does OSPF enabled? if yes then find advertised networks

from ciscoconfparse import CiscoConfParse
from pprint import pprint
Exemple #9
0
#!/usr/bin/python
__author__ = "Melih TEKE"
__EMAIL__ = "*****@*****.**"
from netmiko import ConnectHandler
from ciscoconfparse import CiscoConfParse
from pprint import pprint

iosv_l2_s1 = {
    'device_type': 'cisco_ios',
    'ip': '192.168.178.65',
    'username': '******',
    'password': '******',
}

net_connect = ConnectHandler(**iosv_l2_s1)
output = net_connect.send_command('show runn')
print(output)

with open("output.txt", "w") as f:
    f.write(output)
    f.close()
parsed_config = CiscoConfParse("output.txt")

if parsed_config.has_line_with(r"^router ospf"):
    ospf_config = parsed_config.find_all_children(r"^router ospf")

pprint(ospf_config)