Exemple #1
0
def get_int(switch, interface):
    """ Get a config snippet from a device """

    conf_file = conf_dir + switch + extension

    interface = expand_port(interface)

    try:
        parse = CiscoConfParse(conf_file)
    except:
        print("Error: could not load config for ", conf_file)
        sys.exit(1)

    search_int = "^interface " + interface + "$"



    if args.match:
        m = parse.find_objects_w_child(parentspec=search_int,
            childspec=args.match)
        if m:
            print(args.switch + ',' + args.int + ',' + args.match)

    else:
        iface = parse.find_all_children(search_int)
        if iface:
            print('!' + switch + ' ' + interface)
        for line in iface:
            print(line)
        if iface:
            print('!')
def testValues_find_all_chidren02():
    """Ensure we don't need a comment at the end of a """
    """  parent / child block to identify the end of the family"""
    CONFIG = [
        'thing1',
        ' foo',
        '  bar',
        '   100',
        '   200',
        '   300',
        '   400',
        'thing2',
    ]
    RESULT_CORRECT = [
        'thing1',
        ' foo',
        '  bar',
        '   100',
        '   200',
        '   300',
        '   400',
    ]
    cfg = CiscoConfParse(CONFIG)
    test_result = cfg.find_all_children('^thing1')
    assert RESULT_CORRECT == test_result
Exemple #3
0
def get_int(switch, interface):
    """ Get a config snippet from a device """

    conf_file = conf_dir + switch + extension

    interface = expand_port(interface)

    try:
        parse = CiscoConfParse(conf_file)
    except:
        print("Error: could not load config for ", conf_file)
        sys.exit(1)

    search_int = "^interface " + interface + "$"

    if args.match:
        m = parse.find_objects_w_child(parentspec=search_int,
                                       childspec=args.match)
        if m:
            print(args.switch + ',' + args.int + ',' + args.match)

    else:
        iface = parse.find_all_children(search_int)
        if iface:
            print('!' + switch + ' ' + interface)
        for line in iface:
            print(line)
        if iface:
            print('!')
Exemple #4
0
def conf_to_xml(f):

    ccp = CiscoConfParse(f)
    print ccp

    hostname = ccp.find_lines("^hostname")[0].lower()
    hostname = re.sub("hostname ", "", hostname)

    xmlroot = etree.Element('add')
    doc = etree.Element('doc')
    xmlroot.append(doc)

    f_id = etree.Element('field') 
    f_id.attrib["name"] = "id"
    f_id.text = hostname
    doc.append(f_id)

    f_type = etree.Element('field') 
    f_type.attrib["name"] = "doctype"
    f_type.text = "full config"
    doc.append(f_type)

   
    f_content = etree.Element('field') 
    f_content.attrib["name"] = "content"
    f_content.text = "\n".join(ccp.find_lines(".*"))
    doc.append(f_content)


    types = ['interface', 'router', 'ip vrf', 'ip access-list', 'class-map', 'policy-map']

    for t in types:
        for obj in ccp.find_objects(r"^"+t):

            subdoc = etree.Element('doc') 
            subid = hostname + " " + obj.text 

            subf_id = etree.Element('field') 
            subf_id.attrib["name"] = "id"
            subf_id.text = subid
            subdoc.append(subf_id)

            subf_type = etree.Element('field') 
            subf_type.attrib["name"] = "doctype"
            subf_type.text = t 
            subdoc.append(subf_type)

            subf_content = etree.Element('field') 
            subf_content.attrib["name"] = "content"
            subf_content.text = "\n".join(ccp.find_all_children("^" + obj.text))
            subdoc.append(subf_content)

            doc.append(subdoc)


    xmlstring = etree.tostring(xmlroot, pretty_print=True)
    etree.ElementTree(xmlroot).write(xmldir + "/" + hostname + ".xml")
    def downloadRoustesForClient(self, client):
        #config_files_dir = self.config_files_dirs[country]
        data = {'BRASIL': [], 'MEXICO': []}
        countryDirList = os.listdir(self.root)
        for countryDir in countryDirList:
            countryDirPath = os.path.join(self.root, countryDir)
            peList = os.listdir(countryDirPath)
            print(countryDir)
            bar = progressbar.ProgressBar()
            for pe in bar(peList):
                pePath = os.path.join(countryDirPath, pe)
                with open(pePath) as pe_config:
                    if ".txt" in pe:
                        pe = pe.split(".txt")[0]
                    parse = CiscoConfParse(pe_config)
                    interfaces = parse.find_parents_w_child("^interface", client.get_vrf())

                    if interfaces:
                        for interface in interfaces:
                            wan = ''
                            inter_config = parse.find_all_children("^%s$" % interface)
                            inter_config_string = " ".join(inter_config)

                            if 'vrf' not in inter_config_string or 'address' not in inter_config_string:
                                continue
                            for line in inter_config:
                                line = line.split()
                                # print(line)
                                if 'vrf' in line:
                                    vrf = line[-1]
                                elif 'address' in line:
                                    if line[-2] != 'address':
                                        wan = line[-2]
                                    else:
                                        wan = line[-1][:-4]
                                    # print(data[f]['wan'], f)
                                    wan = generate_ip(wan)
                            if not wan:
                                continue

                            country = Country.objects.get(name=countryDir)

                            if is_xr(pe_config.read()):
                                routes = get_config(country, pe, "show bgp vrf " + vrf + " nei " + wan + " route", list=False)
                            else:
                                routes = get_config(country, pe, "show ip bgp vpnv4 vrf " + vrf + " nei " + wan + " route", list=False)
                            routes = re.findall("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}", routes)

                            if not routes:
                                continue
                            [data[countryDir].append(route) for route in routes]
        client.routes = data
        client.save()
        print('Done')
        return data
Exemple #6
0
def parse_c_map(ws):

    row = 1

    # open all .txt files in the current directory
    for filename in glob.glob('*.txt'):

        config = CiscoConfParse(filename, factory=True, syntax='ios')
        hostname = config.find_objects_dna(r'Hostname')[0].hostname
        ios_ver = config.find_lines('IOS')[0][len('!! IOS XR Configuration '):]
        print('... %s (IOS XR %s)' % (hostname, ios_ver))

        for be in config.find_objects_w_child(r'^interface.+Bundle[^.]+$',
                                              'service-policy output'):
            for parent in be.re_search_children('service-policy'):
                parent_policy = parent.text[len(' service-policy output '):]
                p_map = config.find_all_children(r'^policy-map ' +
                                                 parent_policy + '$')
                child_policy = [i for i in p_map if 'service-policy' in i
                                ][0][len('  service-policy '):]
                for c_policy in config.find_objects('policy-map ' +
                                                    child_policy + '$'):
                    for c_map in c_policy.re_search_children('class'):
                        # write the hostname in column A
                        ws.write(row, 0, hostname)
                        # write the IOS XR version in column B
                        ws.write(row, 1, ios_ver)
                        # write child policy in column C
                        ws.write(row, 2, child_policy)
                        # write class maps in column D
                        ws.write(row, 3, c_map.text[len(' class '):])
                        for police_rate in c_map.re_search_children('police'):
                            # write police rate in column E
                            ws.write(row, 4, police_rate.text.strip())
                        if 'vlan' in c_map.text.lower(
                        ) or 'default' in c_map.text:
                            ws.write(row, 5, 'Ok')
                        else:
                            ws.write(row, 5, 'Incorrect class map.')
                        row += 1

    print('... Completed %s class maps.' % row)

    # set the autofilter
    ws.autofilter(0, 0, row, 5)
Exemple #7
0
def netcompare(origin, target, no_command):
    origin_file = CiscoConfParse(origin, syntax='ios', factory=False)
    target_file = CiscoConfParse(target, syntax='ios', factory=False)
    diff_add_no_commands = []
    for line in origin_file.objs:
        if line.parent.linenum == line.linenum and line.is_config_line is True:
            parent_match = target_file.find_objects('^' +
                                                    re.escape(line.text) + '$',
                                                    exactmatch=True,
                                                    ignore_ws=False)
            if len(parent_match) == 0 and not re.match(no_command + "\s.*",
                                                       line.text):
                diff_add_no_commands.append(no_command + ' ' + line.text)
            elif len(parent_match) == 0 and re.match(no_command + "\s.*",
                                                     line.text):
                line_text_without_no = re.match(no_command + "\s(.*)",
                                                line.text)
                diff_add_no_commands.append(line_text_without_no.group(1))
            if len(line.children) > 0 and len(parent_match) != 0:
                result_comparison = compare_children_prefix_no(
                    line, target_file, no_command)
                if len(result_comparison) > 0:
                    diff_add_no_commands.append(result_comparison)
    diff_add_commands = []
    for line in target_file.objs:
        if line.parent.linenum == line.linenum and line.is_config_line is True:
            parent_match = origin_file.find_objects('^' +
                                                    re.escape(line.text) + '$',
                                                    exactmatch=True,
                                                    ignore_ws=False)
            if len(parent_match) == 0:
                parent_with_children = target_file.find_all_children(
                    '^' + re.escape(line.text) + '$')
                for line_in_parent_with_children in parent_with_children:
                    diff_add_commands.append(line_in_parent_with_children)
            if len(line.children) > 0 and len(parent_match) != 0:
                result_comparison = compare_children(line, origin_file)
                if len(result_comparison) > 0:
                    diff_add_commands.append(
                        compare_children(line, origin_file))
    return merge_commands(diff_add_no_commands, diff_add_commands)
Exemple #8
0
def check_console_password(
        config: typing.List[str]) -> typing.Optional[CheckResult]:
    """Check for authentication on the console line."""
    parsed_config = CiscoConfParse(config)
    line_con_config = parsed_config.find_all_children("^line con 0")
    if len(line_con_config) == 0:
        return None  # TODO: Log this?

    login = False
    password = False
    for line in line_con_config:
        if "login" in line:
            login = True
        if "password" in line:
            password = True

    if not login or not password:
        return CheckResult(text="Console line unauthenticated.",
                           lines=line_con_config)
    else:
        return None
def testValues_find_all_chidren02():
    """Ensure we don't need a comment at the end of a """
    """  parent / child block to identify the end of the family"""
    CONFIG = ['thing1',
        ' foo',
        '  bar',
        '   100',
        '   200',
        '   300',
        '   400',
        'thing2',]
    RESULT_CORRECT = ['thing1',
        ' foo',
        '  bar',
        '   100',
        '   200',
        '   300',
        '   400',]
    cfg = CiscoConfParse(CONFIG)
    test_result = cfg.find_all_children('^thing1')
    assert RESULT_CORRECT==test_result
def netcompare(origin, target, no_command):
    origin_file = CiscoConfParse(origin, syntax='ios', factory=False)
    target_file = CiscoConfParse(target, syntax='ios', factory=False)
    diff_add_no_commands = []
    for line in origin_file.objs:
        if line.parent.linenum == line.linenum and line.is_config_line is True:
            parent_match = target_file.find_objects(
                '^'+re.escape(line.text)+'$',
                exactmatch=True, ignore_ws=False)
            if len(parent_match) == 0 and not re.match(
              no_command + "\s.*", line.text):
                diff_add_no_commands.append(no_command + ' ' + line.text)
            elif len(parent_match) == 0 and re.match(
              no_command + "\s.*", line.text):
                line_text_without_no = re.match(
                  no_command + "\s(.*)", line.text)
                diff_add_no_commands.append(line_text_without_no.group(1))
            if len(line.children) > 0 and len(parent_match) != 0:
                result_comparison = compare_children_prefix_no(
                    line, target_file, no_command)
                if len(result_comparison) > 0:
                    diff_add_no_commands.append(result_comparison)
    diff_add_commands = []
    for line in target_file.objs:
        if line.parent.linenum == line.linenum and line.is_config_line is True:
            parent_match = origin_file.find_objects(
                '^'+re.escape(line.text)+'$',
                exactmatch=True, ignore_ws=False)
            if len(parent_match) == 0:
                parent_with_children = target_file.find_all_children(
                    '^'+re.escape(line.text)+'$')
                for line_in_parent_with_children in parent_with_children:
                    diff_add_commands.append(line_in_parent_with_children)
            if len(line.children) > 0 and len(parent_match) != 0:
                result_comparison = compare_children(line, origin_file)
                if len(result_comparison) > 0:
                    diff_add_commands.append(
                        compare_children(line, origin_file))
    return merge_commands(diff_add_no_commands, diff_add_commands)
Exemple #11
0
def get_outer_config(filename, vrf, outer_encap, basedir, bgpid, fw):
    data = []
    vrfmember = 'vrf ' + vrf
    parse = CiscoConfParse(basedir + filename)

    # Create L2 VLAN
    data.append("vlan " + str(outer_encap))

    # SVI
    for obj in parse.find_objects("interface Vlan" + str(outer_encap)):
        svi = obj.text
        data.append(svi)
        if obj.hash_children != 0:
            for c in obj.children:
                if bool(re.search('ip address', c.text)):
                    ip = c.text
                    ip = ip.replace("ip address ", "")
                    ip = ip.replace("/30", "")
                    ip = ip.strip()
                data.append(c.text)
    # BGP
    bgp_details = parse.find_all_children("^router bgp")
    for d in bgp_details:
        data.append(d)

    # Trunk Link
    if bool(re.search('RES-MMP', vrf)):
        data.append("interface Ethernet2/9")
    else:
        data.append("interface Ethernet2/10")
    data.append(" switchport")
    data.append(" switchport mode trunk")
    data.append(" switchport trunk allowed vlan add " + str(outer_encap))
    data.append(" no shutdown")

    return (ip, data)
Exemple #12
0
def parse_egress(ws):

    row = 1

    # open all .txt files in the current directory
    for filename in glob.glob('*.txt'):

        config = CiscoConfParse(filename, factory=True, syntax='ios')
        hostname = config.find_objects_dna(r'Hostname')[0].hostname
        ios_ver = config.find_lines('IOS')[0][len('!! IOS XR Configuration '):]
        print('... %s (IOS XR %s)' % (hostname, ios_ver))

        # for be in config.find_objects_w_child(r'^interface.+Bundle[^.]+$', 'service-policy output'):
        for be in config.find_objects(r'^interface.+Bundle[^.]+$'):

            # write the hostname in column A
            ws.write(row, 0, hostname)
            # write the IOS XR version in column B
            ws.write(row, 1, ios_ver)
            # write the BE port in column C
            be_port = be.text[len('interface '):]
            ws.write(row, 2, be_port)

            # write the description in column D
            for line in be.re_search_children(r'^ description '):
                description = line.text[len('description '):]
                ws.write(row, 3, description)

            # pre-fill remarks for be ports without parent policies
            ws.write(row, 6, 'Missing parent and/ or child policy.')

            for parent in be.re_search_children('service-policy'):

                # write the parent policy in column E
                parent_policy = parent.text[len(' service-policy output '):]
                parent_policy1 = parent.text[len(' service-policy input '):]
                ws.write(row, 4, parent.text.strip())

                # write the child policy in column F
                try:
                    p_map = config.find_all_children(r'^policy-map ' +
                                                     parent_policy + '$')
                    child_policy = [i for i in p_map if 'service-policy' in i
                                    ][0][len('  service-policy '):]
                    ws.write(row, 5, child_policy)
                except Exception:
                    p_map = config.find_all_children(r'^policy-map ' +
                                                     parent_policy1 + '$')
                    child_policy = [i for i in p_map if 'service-policy' in i
                                    ][0][len('  service-policy '):]
                    ws.write(row, 5, child_policy)

                if 'input' in parent.text:
                    ws.write(
                        row, 6,
                        'Policy incorrectly applied on ingress instead of egress.'
                    )
                elif be_port[len('Bundle-Ether'):] == parent_policy[len('policy_port_BE'):] \
                        and parent_policy[len('policy_port_BE'):] == child_policy[len('policy_BVID_BE'):]:
                    ws.write(row, 6, 'Ok')
                else:
                    ws.write(row, 6, 'Incorrect parent and/ or child policy.')

            row += 1

    print('... Completed %s egress policies.' % row)

    # set the autofilter
    ws.autofilter(0, 0, row, 6)
 def testValues_find_all_children(self):
     ## test find_all_chidren
     for config, args, result_correct in self.find_all_children_Values:
         cfg = CiscoConfParse(config)
         test_result = cfg.find_all_children(**args)
         self.assertEqual(result_correct, test_result)
Exemple #14
0
f = open ('sunspeed_pre_move.csv', 'r')
csv_f = csv.reader(f)
next(csv_f, None)

#output/scratch file with all output data #
sfile = open('new_config_output.txt', 'wa')
 
for row in csv_f:
	servername = row[2]
	serverinterface = row[4]
	configfilename = row[35]
	slotinformation = row[36]
	interfaceinformation = row[37]
	ethinfo = str("interface GigabitEthernet"+slotinformation+"/"+interfaceinformation)
	parse= CiscoConfParse("/home/jp/Documents/Migration_tools/SUNSPEED/CONFIGS/"+configfilename+".inf.uk.cliffordchance.com-Running.config")
	portconfig = parse.find_all_children(ethinfo)
	print (servername+"-"+serverinterface)
	sfile.write("new name is "+servername+"-"+serverinterface +", ") 
# portconfig is a list of all port information found in the config file matched to the interface #
	for line in portconfig:
		if "description" in line:
			desc = line
			print desc
			sfile.write("old name is "+desc+", ")
		if "switchport access" in line:
			vlanid = str(line)
			print str(vlanid)
			sfile.write(vlanid +", ")
		if "speed" in line:
			speed = line
			print speed
Exemple #15
0
from ciscoconfparse import CiscoConfParse
cisco_cfg = CiscoConfParse("running-config.cfg")
#fhand=open('running-config.cfg')
d=dict()
all_children = cisco_cfg.find_all_children('object')
for i in all_children:
        if i.startswith("object"):
            d[i]=cisco_cfg.find_all_children(i)[1:]

for k in d:
   print(k ,d[k])

print(k)


#obj=cisco_cfg.find_objects(r"^object")
#for i in obj:
# i=str(i).split()
# print(i[5], cisco_cfg.find_children(obj))
 #print(cisco_cfg.find_children(i[5]))

 #test GIT
Exemple #16
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)
script_logger(message="*Last Instances is {0}".format(last_instance),
              debug=debug,
              indent=1)

vrf_interfaces = []
for index, instance in enumerate(ri_vrfs):
    print("\n")
    script_logger(message="*Processing Instance:{0}".format(instance),
                  debug=debug)
    if debug.lower() == 'false':
        pprint("Processing instance #{0} out of {1}".format(
            index + 1, len(ri_vrfs)))
        # time.sleep(0.5)
        # subprocess.call("clear")

    instance_config = parse.find_all_children(instance)
    for line in instance_config:
        if "interface " in line:
            vrf_interfaces.append(line.split()[1])

    script_logger(message="*VRF interfaces are {0}".format(vrf_interfaces),
                  debug=debug,
                  indent=2)
    vrf_interfaces = list(set(vrf_interfaces))
    clean_intfs = []
    for intf in vrf_interfaces:
        if ";" not in intf:
            clean_intfs.append(intf)

    vrf_interfaces = clean_intfs
#!/usr/bin/env pytho
'''
This script parses cisco.txt file and searches for 'crypto map CRYPTO' lines using CCP module.
Then it displays childrens indented multiple times for each element of crypto_map variable (list).

'''
import pprint
from ciscoconfparse import CiscoConfParse

fo = open('cisco.txt', 'r')    # Opening text file as FileObject with open() function
parse = CiscoConfParse(fo)   # Loading the file to CCF module as argument for parsing later
crypto_map = parse.find_all_children(r'^crypto map CRYPTO')
# In the line above using find_all_children method with regex (parsing)

print 'Show the content of crypto_map variable: \n',crypto_map
print

print 'Show me parent-child relationships for crypto map CRYPTO lines in cisco.txt file: '
# Iterate over elements of crypto_map list and display in a nice human readable format
for line in crypto_map:
#    pprint.pprint(line)    # Replaced with the below as suggested by Kirk (clean output)
     print(line.strip("\n"))
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')
#!/usr/bin/python
# Getting familiar with ciscoconfparse
# get_ipints.py

__author__ = 'Claudia'

import sys

#raw_input("Press Return to continue...")

from ciscoconfparse import CiscoConfParse

config = CiscoConfParse(str(sys.argv[1]), factory=True)
vl = config.find_all_children("^vlan")
lvl = len(vl)
for v in vl:
    print v
print("Number of items in list: %s" % lvl)
print("Vlans from config file: %s" % str(sys.argv[1]))

raw_input("Press Return to continue to Router/SVI Section...")

int = config.find_objects_w_child(parentspec=r"^interface",
                                  childspec=r"ip address")
lint = len(int)
for i in int:
    print i

print("Number of items in list: %s" % lint)
print("Routed Interfaces from config file: %s" % str(sys.argv[1]))
#!/usr/bin/env python

"""Stefano Pirrello Week 1 Excercise 8 - 11"""

from ciscoconfparse import CiscoConfParse


#Exercise 8 
#The script should find all of the crypto map entries in 
#the file (lines that begin with 'crypto map CRYPTO') and for each crypto map entry print out its children.
config_obj = CiscoConfParse("cisco_ipsec.txt")

cmaps = config_obj.find_all_children(r"crypto map CRYPTO")

# print type(cmaps)
# print len(cmaps)
print "\n\nExercise 8:"

for cmap in cmaps:
	print cmap
	
#Exercies 9
#Find all of the crypto map entries that are using PFS group2
config_obj = CiscoConfParse("cisco_ipsec.txt")
cmaps = config_obj.find_objects(r"crypto map CRYPTO")
print "\n\nExercise 9:"
#cmaps = config_obj.find_all_children(r"crypto map CRYPTO")
cmaps_list = []
for cmap in cmaps:
	if cmap.re_search_children(r"set\spfs\sgroup2"):
		cmaps_list.append(cmap)
#!/usr/bin/python
# get_vlans.py

__author__ = 'Claudia'

import sys

#raw_input("Press Return to continue...")

from ciscoconfparse import CiscoConfParse

config = CiscoConfParse(str(sys.argv[1]))
vl = config.find_all_children("^vlan")
lvl=len(vl)
for v in vl:
    print v
print ("Number of items in list: %s" % lvl)
print ("Vlans from config file: %s" % str(sys.argv[1]))

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

ipint = config.find_objects_w_child(parentspec=r"^interface",childspec=r"ip address")
lipint = len(ipint)
for i in ipint:
    print i

print ("Number of items in list: %s" % lipint)
print ("IPs from config file: %s" % str(sys.argv[1]))
#!/usr/bin/env pytho
'''
This script parses cisco.txt file and searches for 'crypto map CRYPTO' lines using CCP module.
Then it displays childrens indented multiple times for each element of crypto_map variable (list).

'''
import pprint
from ciscoconfparse import CiscoConfParse

fo = open('cisco.txt',
          'r')  # Opening text file as FileObject with open() function
parse = CiscoConfParse(
    fo)  # Loading the file to CCF module as argument for parsing later
crypto_map = parse.find_all_children(r'^crypto map CRYPTO')
# In the line above using find_all_children method with regex (parsing)

print 'Show the content of crypto_map variable: \n', crypto_map
print

print 'Show me parent-child relationships for crypto map CRYPTO lines in cisco.txt file: '
# Iterate over elements of crypto_map list and display in a nice human readable format
for line in crypto_map:
    #    pprint.pprint(line)    # Replaced with the below as suggested by Kirk (clean output)
    print(line.strip("\n"))
Exemple #24
0
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

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

if orig_config.has_line_with(r"^router ospf"):
    ospf_config = orig_config.find_all_children(r"^router ospf")
    networks = []
    for line in ospf_config:
        if 'network' in line:
            networks.append(line.split(" ")[2])

    print networks

orig_config.find
 SERVICEPOLICY_RE = re.compile(r'service-policy\soutput\s(\S+)')
 INTERFACE_RE = re.compile(r'^interface\s(\S+)')
 CLASS_MAP_RE = re.compile(r'^class-map\smatch-any\s(\S+)')
 # Loop through the interfaces, looking for service-policy output.
 for intobj in interfaces:
     # if the interface has an output service-policy jump in
     if intobj.re_search_children("service-policy output"):
         # Find the class-map children of the policy-map - line terminated to stop half matches
         class_maps_t = parse.find_children("policy-map " + intobj.re_match_iter_typed(SERVICEPOLICY_RE, result_type=str) + "$")
         # CiscoConfParse helpfully includes the parent config, which we don't need so we remove it.
         class_maps_t.remove ("policy-map " + intobj.re_match_iter_typed(SERVICEPOLICY_RE, result_type=str))
         # If there's only on class-map, it's a parent policy in a hirearchical shaper
         if len(class_maps_t) == 1:
             policy_map_parent = intobj.re_match_iter_typed(SERVICEPOLICY_RE, result_type=str)
             # Find all the children of the parent policy
             policy_map_c = parse.find_all_children("policy-map " + intobj.re_match_iter_typed(SERVICEPOLICY_RE, result_type=str))
             # Step through them looking for the child policy-map name
             for pmap_p_child in policy_map_c:
                 pmap_p_child_policy = re.search(r"service-policy (\S+)", pmap_p_child)
                 if pmap_p_child_policy:
                      # We've found it - set the child policy name
                      child_policy = pmap_p_child_policy.group(1)
                      class_maps_t = []
                      # Get the class maps for the policy-map
                      class_maps_t = parse.find_children(r"policy-map " + pmap_p_child_policy.group(1) + "$")
                      # Remove the parent policy-map config - it's not useful to us
                      class_maps_t.remove ("policy-map " + pmap_p_child_policy.group(1))
         else:
             # We've found more than one class-map so this must be parent policy directly on the interface 
             policy_map_parent = "No Parent"
             # Set the policy name
Exemple #26
0
def parse_ingress(ws):

    row = 1

    # open all .txt files in the current directory
    for filename in glob.glob('*.txt'):

        config = CiscoConfParse(filename, factory=True, syntax='ios')
        hostname = config.find_objects_dna(r'Hostname')[0].hostname
        ios_ver = config.find_lines('IOS')[0][len('!! IOS XR Configuration '):]
        print('... %s (IOS XR %s)' % (hostname, ios_ver))

        for ports in config.find_objects_w_child('^interface.+l2transport',
                                                 'service-policy input'):

            # write the hostname in column A
            ws.write(row, 0, hostname)
            # write the IOS XR version in column B
            ws.write(row, 1, ios_ver)
            # write the ingress port in column C
            port = ports.text[len('interface '):-len(' l2transport')]
            ws.write(row, 2, port)

            for line in ports.re_search_children(r'^ description '):
                description = line.text[len('description '):]
                ws.write(row, 3, description)

            for maps in ports.re_search_children('service-policy'):

                # write the ingress policy map in column D
                policy_map = maps.text[len(' service-policy input '):]
                ws.write(row, 4, policy_map)
                policy_maps = config.find_all_children(policy_map)
                policy_rate = [i for i in policy_maps
                               if 'police rate' in i][0].strip()
                cos = [i for i in policy_maps if 'set cos' in i][0].strip()
                ws.write(row, 5, policy_rate)
                # write the COS setting in column F
                ws.write(row, 6, cos)

                # determine the circuit type based on the policy names
                if 'aovl' in policy_map.lower():
                    circuit_type = 'Adva Overlay'
                elif ('test' in policy_map.lower()) or ('mef'
                                                        in policy_map.lower()):
                    circuit_type = 'Test'
                elif ('nid' in policy_map.lower()) or ('dcn'
                                                       in policy_map.lower()):
                    circuit_type = 'DCN'
                else:
                    circuit_type = 'Customer'

                # write the circuit type in column G
                ws.write(row, 7, circuit_type)

                if circuit_type == 'Test':
                    if 'cos 4' in cos:
                        ws.write(row, 8, 'Ok')
                    else:
                        ws.write(
                            row, 8, 'Matched keyword test and/ or MEF.'
                            'Please confirm if this is a test policy and delete. '
                            'If not, change/ add set cos 4.')

                elif circuit_type == 'Adva Overlay':
                    if 'cos 6' in cos:
                        ws.write(row, 8, 'Ok')
                    else:
                        ws.write(row, 8, 'Change to set cos 6.')

                elif circuit_type == 'DCN':
                    if ('cos 4' in cos) or ('cos 7' in cos):
                        ws.write(row, 8, 'Ok')
                    else:
                        ws.write(row, 8, 'DCN circuit - change set to cos 7.')

                elif circuit_type == 'Customer':
                    if 'cos 4' in cos:
                        ws.write(row, 8, 'Ok')
                    else:
                        ws.write(row, 8, 'Change/ add set cos 4.')

                cos = ''
                row += 1

    print('... Completed %s ingress policies.' % row)

    # set the autofilter
    ws.autofilter(0, 0, row, 8)
Exemple #27
0
#!/usr/bin/python
# get_vlans.py

__author__ = 'Claudia'

import sys

#raw_input("Press Return to continue...")

from ciscoconfparse import CiscoConfParse

config = CiscoConfParse(str(sys.argv[1]))
vl = config.find_all_children("^vlan")
lvl = len(vl)
for v in vl:
    print v
print("Number of items in list: %s" % lvl)
print("Vlans from config file: %s" % str(sys.argv[1]))

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

ipint = config.find_objects_w_child(parentspec=r"^interface",
                                    childspec=r"ip address")
lipint = len(ipint)
for i in ipint:
    print i

print("Number of items in list: %s" % lipint)
print("IPs from config file: %s" % str(sys.argv[1]))
Exemple #28
0
def parse_cisco_files(Full_Path_File_Nmae,outdirname,csvfilename):

 

    with io.open(outdirname + "/" + csvfilename,'w',encoding='ascii',errors='replace') as out_file:  

            writer = csv.writer(out_file)

            writer.writerow(('Router_Name','Entry_Type','Entry_Type_Seq','Entry_Name','Child_Seq','Child_Name'))

            

            for path, dirs, files in os.walk(dirname):

 

                for filename in files:

                    if fnmatch.fnmatch(filename, '*.Config'):

                        cfg_file = os.path.abspath(os.path.join(path, filename))

                        f = open(cfg_file)

                        line = f.read()

                        first_line = line.split('\n', 1)[0]

                        if re.search('^!$', first_line):

           

                #            parse = CiscoConfParse(Full_Path_File_Nmae)

                           

                            parse = CiscoConfParse(cfg_file)

                           

                    

                            print(parse)

                   

                            router_name = parse.find_lines("^hostname")

#                            writer.writerow(("".join(router_name),'service','Test','Test','NA','NA'))

                   

                            #Return a list of all Header   

                            service = parse.find_lines("^service")     

                            boot = parse.find_lines("^boot") 

                            security = parse.find_lines("^security")

                            logging = parse.find_lines("^logging")

                            no = parse.find_lines("^no")

                            

                            print("\n")

                            for service_i,service_j in enumerate(service):

                                print("".join(router_name),"\t",'service',"\t" ,service_i,"\t",service_j)

                                writer.writerow(("".join(router_name),'service',service_i,service_j,'NA','NA'))

                            

                            

                            for boot_i,boot_j in enumerate(boot):

                                print("".join(router_name),"\t", 'boot',"\t",boot_i,"\t",boot_j)

                                writer.writerow(("".join(router_name),'boot',boot_i,boot_j,'NA','NA'))

                             

                            for security_i,security_j in enumerate(security):

                               print("".join(router_name),"\t", 'security',"\t",security_i,"\t",security_j)

                                writer.writerow(("".join(router_name),'security',security_i,security_j,'NA','NA'))

                                

                            for logging_i,logging_j in enumerate(logging):

                                print("".join(router_name),"\t", 'logging',"\t",logging_i,"\t",logging_j)   

                                writer.writerow(("".join(router_name),'logging',logging_i,logging_j,'NA','NA'))

                            

                            for no_i,no_j in enumerate(no):

                                print("".join(router_name),"\t", 'no',"\t",no_i,"\t",no_j)

                                writer.writerow(("".join(router_name),'no',no_i,no_j,'NA','NA'))

                            

                            

                            # Return a list of all policy accounting and subinterfaces         

                            aaa = parse.find_lines("^aaa")       

                            

                            for aaa_i,aaa_j in enumerate(aaa):

                            #    print("\n", i,"\t",j)

                                chld_aaa = parse.find_all_children(aaa_j)

                            #    print(len(chld))

                                if len(chld_aaa) >=1 :

                                    for aaa_k,aaa_m in enumerate(chld_aaa):

                                        print( "".join(router_name),"\t", 'aaa',"\t",aaa_i,"\t",aaa_j,"\t",aaa_k,"\t",aaa_m)

                                        writer.writerow(("".join(router_name),'no',aaa_i,aaa_j,aaa_k,aaa_m))

                                else:

                                    print( "".join(router_name),"\t", 'aaa',"\t",aaa_i,"\t",aaa_j)

                                    writer.writerow(("".join(router_name),'aaa',aaa_i,aaa_j,'NA','NA'))

                           

                            

                            # Return a list of all clock         

                            clock = parse.find_lines("^clock")       

                            

                            for clock_i,clock_j in enumerate(clock):

                            #    print("\n", i,"\t",j)

                                chld_clock = parse.find_all_children(clock_j)

                            #    print(len(chld))

                                if len(chld_clock) >=1 :

                                    for clock_k,clock_m in enumerate(chld_clock):

                                        print( "".join(router_name),"\t", 'clock',"\t",clock_i,"\t",clock_j,"\t",clock_k,"\t",clock_m)

                                        writer.writerow(("".join(router_name),'clock',clock_i,clock_j,clock_k,clock_m))

                                else:

                                    print( "".join(router_name),"\t", 'clock',"\t",clock_i,"\t",clock_j)

                    ######  TO DO                

                                    writer.writerow(("".join(router_name),'clock',clock_i,clock_j,'NA','NA'))

                           

                            

                            # Return a list of all dot         

                            dot = parse.find_lines("^dot")       

                            

                            for dot_i,dot_j in enumerate(dot):

                            #    print("\n", i,"\t",j)

                                chld_dot = parse.find_all_children(dot_j)

                            #    print(len(chld))

                                if len(chld_dot) >=1 :

                                    for dot_k,dot_m in enumerate(chld_dot):

                                        print( "".join(router_name),"\t", 'dot',"\t",dot_i,"\t",dot_j,"\t",dot_k,"\t",dot_m)

                                        writer.writerow(("".join(router_name),'dot',dot_i,dot_j,dot_k,dot_m))

                                else:

                                    print( "".join(router_name),"\t", 'dot',"\t",dot_i,"\t",dot_j)

                                    writer.writerow(("".join(router_name),'dot',dot_i,dot_j,'NA','NA'))

                           

                            

                            # Return a list of all ip         

                            ip1 = parse.find_lines("^ip ")  

                            

                            for ip1_a,ip1_b in enumerate(ip1):

                            #     print(a,b)       

                                 chld_ip = parse.find_all_children(ip1_b)

                                 if len(chld_ip) >=1 :

                                     for ip1_k,ip1_m in enumerate(chld_ip):

                                         print( "".join(router_name),"\t", 'ip',"\t",ip1_a,"\t",ip1_b,"\t",ip1_k,"\t",ip1_m)

                                         writer.writerow(("".join(router_name),'ip',ip1_a,ip1_b,ip1_k,ip1_m))

                                 else:

                                    print("".join(router_name),"\t", 'ip',"\t",ip1_a,"\t",ip1_b)

                                    writer.writerow(("".join(router_name),'ip',ip1_a,ip1_b,'NA','NA'))

                           

                            

                            

                            # Return a list of all multilink         

                            multilink = parse.find_lines("^multilink")  

                            

                            for multilink_a,multilink_b in enumerate(multilink):

                            #     print(a,b)       

                                 chld_multilink = parse.find_all_children(multilink_b)

                                 if len(chld_multilink) >=1 :

                                     for multilink_k,multilink_m in enumerate(chld_ip):

                                         print( "".join(router_name),"\t", 'multilink',"\t",multilink_a,"\t",multilink_b,"\t",multilink_k,"\t",multilink_m)

                                         writer.writerow(("".join(router_name),'multilink',multilink_a,multilink_b,multilink_k,multilink_m))

                                 else:

                                    print("".join(router_name),"\t", 'multilink',"\t",multilink_a,"\t",multilink_b)

                                    writer.writerow(("".join(router_name),'multilink',multilink_a,multilink_b,'NA','NA'))

                           

                                    

                            voice_card = parse.find_lines("^voice-card")  

                            

                            for voice_card_a,voice_card_b in enumerate(voice_card):

                            #     print(a,b)       

                                 chld_voice_card = parse.find_all_children(voice_card_b)

                                 if len(chld_voice_card) >=1 :

                                     for voice_card_k,voice_card_m in enumerate(chld_voice_card):

                                         print( "".join(router_name),"\t", 'voice_card',"\t",voice_card_a,"\t",voice_card_b,"\t",voice_card_k,"\t",voice_card_m)

                                         writer.writerow(("".join(router_name),'voice_card',voice_card_a,voice_card_b,voice_card_k,voice_card_m))

                                 else:

                                    print("".join(router_name),"\t", 'voice_card',"\t",voice_card_a,"\t",voice_card_b)

                                    writer.writerow(("".join(router_name),'voice_card',voice_card_a,voice_card_b,'NA','NA'))

                                   

                            vtp = parse.find_lines("^vtp")  

                            

                            for vtp_a,vtp_b in enumerate(vtp):

                            #     print(a,b)       

                                 chld_vtp = parse.find_all_children(vtp_b)

                                 if len(chld_vtp) >=1 :

                                     for vtp_k,vtp_m in enumerate(chld_vtp):

                                         print( "".join(router_name),"\t", 'vtp',"\t",vtp_a,"\t",vtp_b,"\t",vtp_k,"\t",vtp_m)

                                         writer.writerow(("".join(router_name),'vtp',vtp_a,vtp_b,vtp_k,vtp_m))

                                 else:

                                    print("".join(router_name),"\t", 'vtp',"\t",vtp_a,"\t",vtp_b)

                                    writer.writerow(("".join(router_name),'vtp',vtp_a,vtp_b,'NA','NA'))

                                   

                            username = parse.find_lines("^username")  

                            

                            for username_a,username_b in enumerate(username):

                            #     print(a,b)       

                                 chld_username = parse.find_all_children(username_b)

                                 if len(chld_username) >=1 :

                                     for username_k,username_m in enumerate(chld_username):

                                         print( "".join(router_name),"\t", 'username',"\t",username_a,"\t",username_b,"\t",username_k,"\t",username_m)

                                         writer.writerow(("".join(router_name),'username',username_a,username_b,username_k,username_m))

                                 else:

                                    print("".join(router_name),"\t", 'username',"\t",username_a,"\t",username_b)

                                    writer.writerow(("".join(router_name),'username',username_a,username_b,'NA','NA'))

                                   

                            archive = parse.find_lines("^archive")  

                            

                            for archive_a,archive_b in enumerate(archive):

                            #     print(a,b)       

                                 chld_archive = parse.find_all_children(archive_b)

                                 if len(chld_archive) >=1 :

                                     for archive_k,archive_m in enumerate(chld_archive):

                                         print( "".join(router_name),"\t", 'archive',"\t",archive_a,"\t",archive_b,"\t",archive_k,"\t",archive_m)

                                         writer.writerow(("".join(router_name),'archive',archive_a,archive_b,archive_k,archive_m))

                                 else:

                                    print("".join(router_name),"\t", 'archive',"\t",archive_a,"\t",archive_b)

                                    writer.writerow(("".join(router_name),'archive',archive_a,archive_b,'NA','NA'))

                                   

                                    

                                    

                            class1 = parse.find_lines("^class")  

                            

                            for class_a,class_b in enumerate(class1):

                            #     print(a,b)       

                                 chld_class = parse.find_all_children(class_b)

                                 if len(chld_class) >=1 :

                                     for class_k,class_m in enumerate(chld_class):

                                         print( "".join(router_name),"\t", 'class',"\t",class_a,"\t",class_b,"\t",class_k,"\t",class_m)

                                         writer.writerow(("".join(router_name),'class',class_a,class_b,class_k,class_m))

                                 else:

                                    print("".join(router_name),"\t", 'class',"\t",class_a,"\t",class_b)

                                    writer.writerow(("".join(router_name),'class',class_a,class_b,'NA','NA'))

                                   

                                    

                                    

                            policy = parse.find_lines("^policy")  

                            

                            for policy_a,policy_b in enumerate(policy):

                            #     print(a,b)       

                                 chld_policy = parse.find_all_children(policy_b)

                                 if len(chld_policy) >=1 :

                                     for policy_k,policy_m in enumerate(chld_policy):

                                         print( "".join(router_name),"\t", 'policy',"\t",policy_a,"\t",policy_b,"\t",policy_k,"\t",policy_m)

                                         writer.writerow(("".join(router_name),'policy',policy_a,policy_b,policy_k,policy_m))

                                 else:

                                    print("".join(router_name),"\t", 'policy',"\t",policy_a,"\t",policy_b)

                                    writer.writerow(("".join(router_name),'policy',policy_a,policy_b,'NA','NA'))

                                    

                                    

                            interface = parse.find_lines("^interface")  

                            

                            for interface_a,interface_b in enumerate(interface):

                            #     print(a,b)       

                                 chld_interface = parse.find_all_children(interface_b)

                                 if len(chld_interface) >=1 :

                                     for interface_k,interface_m in enumerate(chld_interface):

                                         print( "".join(router_name),"\t", 'interface',"\t",interface_a,"\t",interface_b,"\t",interface_k,"\t",interface_m)

                                         writer.writerow(("".join(router_name),'interface',interface_a,interface_b,interface_k,interface_m))

                                 else:

                                    print("".join(router_name),"\t", 'interface',"\t",interface_a,"\t",interface_b)

                                    writer.writerow(("".join(router_name),'interface',interface_a,interface_b,'NA','NA'))

                                   

                                    

                            router1 = parse.find_lines("^router")  

                            

                            for router_a,router_b in enumerate(router1):

                            #     print(a,b)       

                                 chld_router = parse.find_all_children(router_b)

                                 if len(chld_router) >=1 :

                                     for router_k,router_m in enumerate(chld_router):

                                         print( "".join(router_name),"\t", 'router',"\t",router_a,"\t",router_b,"\t",router_k,"\t",router_m)

                                         writer.writerow(("".join(router_name),'router',router_a,router_b,router_k,router_m))

                                 else:

                                    print("".join(router_name),"\t", 'router',"\t",router_a,"\t",router_b)

                                    writer.writerow(("".join(router_name),'router',router_a,router_b,'NA','NA'))

                            

                                

                            address = parse.find_lines("^address")  

                            

                            for address_a,address_b in enumerate(address):

                            #     print(a,b)       

                                 chld_address = parse.find_all_children(address_b)

                                 if len(chld_address) >=1 :

                                     for address_k,address_m in enumerate(chld_address):

                                         print( "".join(router_name),"\t", 'address',"\t",address_a,"\t",address_b,"\t",address_k,"\t",address_m)

                                         writer.writerow(("".join(router_name),'address',address_a,address_b,address_k,address_m))

                                 else:

                                    print("".join(router_name),"\t", 'address',"\t",address_a,"\t",address_b)

                                    writer.writerow(("".join(router_name),'address',address_a,address_b,'NA','NA'))

                                   

                                    

                            # Return a list of all Permit access-list 23 permit

                            #==============================================================================

                            all_access_list = parse.find_lines("^access-list*") 

                            for a_all_access_list,b_all_access_list in enumerate(all_access_list):

                            #     print("".join(router_name),"\t","all_access_list","\t",a_all_access_list,"\t",b_all_access_list)

                                 try:

                                     chld_all_access_list = parse.find_all_children(b_all_access_list)

                                     if len(chld_all_access_list) >=1 :

                                         for access_k,access_m in enumerate(chld_all_access_list):

                                             print( "".join(router_name),"\t", 'all_access_list',"\t",a_all_access_list,"\t",b_all_access_list,"\t",access_k,"\t",access_m)

                                             writer.writerow(("".join(router_name),'all_access_list',a_all_access_list,b_all_access_list,access_k,access_m))

                                 except:

                                    print("".join(router_name),"\t","all_access_list","\t",a_all_access_list,"\t",b_all_access_list)

                                    writer.writerow(("".join(router_name),'all_access_list',a_all_access_list,b_all_access_list,'NA','NA'))

                                        

                                     

                            

                                   

                            route = parse.find_lines("^route")  

                            

                            for route_a,route_b in enumerate(route):

                            #     print(a,b)       

                                 chld_route = parse.find_all_children(route_b)

                                 if len(chld_route) >=1 :

                                     for route_k,route_m in enumerate(chld_route):

                                         print( "".join(router_name),"\t", 'route',"\t",route_a,"\t",route_b,"\t",route_k,"\t",route_m)

                                         writer.writerow(("".join(router_name),'route',route_a,route_b,route_k,route_m))

                                 else:

                                    print("".join(router_name),"\t", 'route',"\t",route_a,"\t",route_b)

                                    writer.writerow(("".join(router_name),'route',route_a,route_b,'NA','NA'))

                                     

                            snmp = parse.find_lines("^snmp")  

                            

                            for snmp_a,snmp_b in enumerate(snmp):

                            #     print(a,b)       

                                 chld_snmp = parse.find_all_children(snmp_b)

                                 if len(chld_snmp) >=1 :

                                     for snmp_k,snmp_m in enumerate(chld_snmp):

                                         print( "".join(router_name),"\t", 'snmp',"\t",snmp_a,"\t",snmp_b,"\t",snmp_k,"\t",snmp_m)

                                         writer.writerow(("".join(router_name),'snmp',snmp_a,snmp_b,snmp_k,snmp_m))

                                 else:

                                    print("".join(router_name),"\t", 'snmp',"\t",snmp_a,"\t",snmp_b)

                                    writer.writerow(("".join(router_name),'snmp',snmp_a,snmp_b,'NA','NA'))

                                   

                            tacacs = parse.find_lines("^tacacs")  

                            

                            for tacacs_a,tacacs_b in enumerate(tacacs):

                            #     print(a,b)       

                                 chld_tacacs = parse.find_all_children(tacacs_b)

                                 if len(chld_tacacs) >=1 :

                                     for tacacs_k,tacacs_m in enumerate(chld_tacacs):

                                         print( "".join(router_name),"\t", 'tacacs',"\t",tacacs_a,"\t",tacacs_b,"\t",tacacs_k,"\t",tacacs_m)

                                         writer.writerow(("".join(router_name),'tacacs',tacacs_a,tacacs_b,tacacs_k,tacacs_m))

                                 else:

                                    print("".join(router_name),"\t", 'tacacs',"\t",tacacs_a,"\t",tacacs_b)

                                    writer.writerow(("".join(router_name),'tacacs',tacacs_a,tacacs_b,'NA','NA'))

                                 

                            control = parse.find_lines("^control")  

                            

                            for control_a,control_b in enumerate(control):

                            #     print(a,b)       

                                 chld_control = parse.find_all_children(control_b)

                                 if len(chld_control) >=1 :

                                     for control_k,control_m in enumerate(chld_control):

                                         print( "".join(router_name),"\t", 'control',"\t",control_a,"\t",control_b,"\t",control_k,"\t",control_m)

                                         writer.writerow(("".join(router_name),'control',control_a,control_b,control_k,control_m))

                                 else:

                                    print("".join(router_name),"\t", 'control',"\t",control_a,"\t",control_b)

                                    writer.writerow(("".join(router_name),'control',control_a,control_b,'NA','NA'))

                                   

                            banner = parse.find_lines("^banner")  

                            

                            for banner_a,banner_b in enumerate(banner):

                            #     print(a,b)       

                                 chld_banner = parse.find_all_children(banner_b)

                                 if len(chld_banner) >=1 :

                                     for banner_k,banner_m in enumerate(chld_banner):

                                         print( "".join(router_name),"\t", 'banner',"\t",banner_a,"\t",banner_b,"\t",banner_k,"\t",banner_m)

                                         writer.writerow(("".join(router_name),'banner',banner_a,banner_b,banner_k,banner_m))

                                 else:

                                    print("".join(router_name),"\t", 'banner',"\t",banner_a,"\t",banner_b)

                                    writer.writerow(("".join(router_name),'banner',banner_a,banner_b,'NA','NA'))

                                   

                            line = parse.find_lines("^line")  

                            

                            for line_a,line_b in enumerate(line):

                            #     print(a,b)       

                                 chld_line = parse.find_all_children(line_b)

                                 if len(chld_line) >=1 :

                                     for line_k,line_m in enumerate(chld_line):

                                         print( "".join(router_name),"\t", 'line',"\t",line_a,"\t",line_b,"\t",line_k,"\t",line_m)

                                         writer.writerow(("".join(router_name),'line',line_a,line_b,line_k,line_m))

                                 else:

                                    print("".join(router_name),"\t", 'line',"\t",line_a,"\t",line_b)

                                    writer.writerow(("".join(router_name),'line',line_a,line_b,'NA','NA'))

                                 

                            scheduler = parse.find_lines("^scheduler")  

                            

                            for scheduler_a,scheduler_b in enumerate(scheduler):

                            #     print(a,b)       

                                 chld_scheduler = parse.find_all_children(scheduler_b)

                                 if len(chld_scheduler) >=1 :

                                     for scheduler_k,scheduler_m in enumerate(chld_scheduler):

                                         print( "".join(router_name),"\t", 'scheduler',"\t",scheduler_a,"\t",scheduler_b,"\t",scheduler_k,"\t",scheduler_m)

                                         writer.writerow(("".join(router_name),'scheduler',scheduler_a,scheduler_b,scheduler_k,scheduler_m))

                                 else:

                                    print("".join(router_name),"\t", 'scheduler',"\t",scheduler_a,"\t",scheduler_b)

                                    writer.writerow(("".join(router_name),'scheduler',scheduler_a,scheduler_b,'NA','NA'))

                                  

                                    

                            ntp = parse.find_lines("^ntp")  

                            

                            for ntp_a,ntp_b in enumerate(ntp):

                            #     print(a,b)       

                                 chld_ntp = parse.find_all_children(ntp_b)

                                 if len(chld_ntp) >=1 :

                                     for ntp_k,ntp_m in enumerate(chld_ntp):

                                         print( "".join(router_name),"\t", 'ntp',"\t",ntp_a,"\t",ntp_b,"\t",ntp_k,"\t",ntp_m)

                                         writer.writerow(("".join(router_name),'ntp',ntp_a,ntp_b,ntp_k,ntp_m))

                                 else:

                                    print("".join(router_name),"\t", 'ntp',"\t",ntp_a,"\t",ntp_b)

                                    writer.writerow(("".join(router_name),'ntp',ntp_a,ntp_b,'NA','NA'))
Exemple #29
0
from ciscoconfparse import CiscoConfParse
import re
import ipaddress
#####################################################
acl_list = list()
obj_list = list()
obj_dict = dict()
acl_dict = dict()
#####################################################

#подаем на вход скрипту файл running-config
cisco_cfg = CiscoConfParse("running-config.cfg")

# поиск применненных acl на интерфейсах
all_acl = cisco_cfg.find_all_children('access-group')
#network_group=list()
#service_group=list()
#ip_simple=list()

#print ('before cycle', all_acl)

#находим наименование access-листов и создаем массив acl:all aces
for i in all_acl:
    acl_list.append(i.split()[1])
#print('afte loop objects', acl_list)
for acl in acl_list:
    acl_dict[acl] = cisco_cfg.find_all_children('access-list ' + acl)
    #print(acl,'\n\n', acl_dict[acl], '\n\n\n\n')
    for e in acl_dict[acl]:
        #print(e)
        #n=n+1
Exemple #30
0
def validateconfigWAN(devconfig):
    parse = CiscoConfParse(io.StringIO(devconfig), syntax='ios')
    intf_hostname = parse.re_match_iter_typed(r'^hostname\s+(\S+)', default='')
    devpolicy = ''
    csize = '0'
    interface = ''
    output = ''
    hasShaper = False
    flag = False
    policy = ''
    cspeed = '0'
    returnpolicy = []
    returncspeed = []
    returninterface = []
    returnhasShaper = []
    returnflag = []

    for intf_obj in parse.find_objects('^interface'):
        intf_name = intf_obj.re_match_typed('^interface\s+(\S.+?)$')

        # Search children of all interfaces for a regex match and return
        # the value matched in regex match group 1.  If there is no match,
        # return a default value: ''

        intf_desc = intf_obj.re_match_iter_typed(
            r"( description (?P<description>.*))\n",
            result_type=str,
            group=2,
            default='')
        intf_policy = intf_obj.re_match_iter_typed(
            r'service-policy\soutput\s(\w+\-\w+\-\w+\-\w+)\s',
            result_type=str,
            group=1,
            default='')
        if intf_policy:
            output = output + "{0}\t{2}\t{1}".format(intf_name, intf_policy,
                                                     intf_desc)
            interface = intf_name
            devpolicy = intf_policy
            desc = intf_desc.split(',')

            try:
                desc = desc[3]
            except:
                policy = 'Not a valid speed in circuit description'
                cspeed = 0
                result = 'Invalid Circuit Description'
                writefile = intf_hostname + '\t' + output + '\t' + result
                with open('C:\\scripts_logs\\QoS2\\' + username + '.log',
                          'a') as f:
                    f.write(writefile)
                    f.write('\n')
                flag = True
                return [
                    policy, cspeed, interface, hasShaper, flag, intf_hostname
                ]

            desc = desc.split(':')

            try:
                csize = desc[1].strip('mbMBgG')
            except:
                policy = 'Not a valid speed in circuit description'
                cspeed = 0
                result = 'Invalid Circuit Description'
                writefile = intf_hostname + '\t' + output + '\t' + result
                with open('C:\\scripts_logs\\QoS2\\' + username + '.log',
                          'a') as f:
                    f.write(writefile)
                    f.write('\n')
                flag = True
                return [
                    policy, cspeed, interface, hasShaper, flag, intf_hostname
                ]

            cspeed = float(csize)
            if cspeed == 1.5:
                policy = "QOS-WAN-T1-EGRESS"
            elif cspeed > 1.5 and cspeed <= 30:
                policy = "QOS-WAN-LBW-EGRESS"
            elif cspeed > 30 and cspeed <= 155:
                policy = "QOS-WAN-MBW-EGRESS"
            elif cspeed > 155:
                policy = "QOS-WAN-HBW-EGRESS"
            else:
                policy = "Not a valid speed in circuit description"

            for intf_obj in parse.find_objects(
                    r'^\s*policy-map\s(\w+\-\w+\-\w+\-\w+)M'):
                intf_policy = intf_obj.re_match_typed(
                    r'^\s*policy-map\s(\w+\-\w+\-\w+\-\w+)')
                if intf_policy == devpolicy:
                    hasShaper = True
                    childlist = parse.find_all_children(intf_obj.text)
                    x = 0
                    while x < len(childlist):
                        if 'service-policy' in childlist[x]:
                            devpolicy = childlist[x]
                            devpolicy = devpolicy.strip('service-policy ')
                            devpolicy = devpolicy.strip('\n')
                        x += 1

            if policy == devpolicy:
                result = 'Correct Policy'
            else:
                result = 'Incorrect Policy'

            writefile = intf_hostname + '\t' + output + '\t' + result
            with open('C:\\scripts_logs\\QoS2\\' + username + '.log',
                      'a') as f:
                f.write(writefile)
                f.write('\n')
            output = ''
            returnpolicy.append(policy)
            returncspeed.append(cspeed)
            returninterface.append(interface)
            returnhasShaper.append(hasShaper)
            returnflag.append(flag)
            devpolicy = ''
            csize = '0'
            interface = ''
            output = ''
            hasShaper = False
            flag = False
            policy = ''
            cspeed = '0'

    return [
        returnpolicy, returncspeed, returninterface, returnhasShaper,
        returnflag, intf_hostname
    ]
def ios_get_vrf_config(conf_file, vrf_name):
    parse = CiscoConfParse(conf_file)
    buff_vrf_name = ""
    buff_vrf_name = "ip vrf " + vrf_name
    return parse.find_all_children(buff_vrf_name)
Exemple #32
0
    
    # Push the "output" thru CiscoConfParse
    # http://www.pennington.net/py/ciscoconfparse/
    parse = CiscoConfParse(output)

    obj_list = []
    obj_list = parse.find_objects(r'hostname')
    if obj_list:
                hostname = obj_list[0].re_match(r'hostname\s(\S+)$')
                print ("Grabbed config from: " + hostname)
    else:
                f_run.write(switch + ",Config grab failed \n")
                continue

    router_bgp = parse.find_all_children(r'router\sbgp\s\d+$')
    if router_bgp:
        bgp_as_grab = re.search(r"router\sbgp\s(\d+)", router_bgp[0])
        bgp_as = bgp_as_grab.group(1)
        for line in router_bgp:
            network_line = bgp_reg_ex.search(line)
            if network_line:
                f_run.write(switch + "," + hostname + "," + bgp_as + "," + network_line.group(1) + "," + network_line.group(2) + "," + str(iptools.ipv4.ip2long(network_line.group(1))) + "," + str(iptools.ipv4.netmask2prefix(network_line.group(2))) + "\n")
    else:
        f_run.write(switch + "," + "No BGP found?")

    
    #f_run.write(kdkdkdkdk)
f_run.close()

#!/usr/bin/python
# Getting familiar with ciscoconfparse
# get_ipints.py

__author__ = 'Claudia'

import sys

#raw_input("Press Return to continue...")

from ciscoconfparse import CiscoConfParse

config = CiscoConfParse(str(sys.argv[1]),factory=True)
vl = config.find_all_children("^vlan")
lvl=len(vl)
for v in vl:
    print v
print ("Number of items in list: %s" % lvl)
print ("Vlans from config file: %s" % str(sys.argv[1]))

raw_input("Press Return to continue to Router/SVI Section...")

int = config.find_objects_w_child(parentspec=r"^interface",childspec=r"ip address")
lint = len(int)
for i in int:
    print i

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

#!/usr/bin/env pytho
'''
This script parses cisco.txt file and searches for 'crypto map CRYPTO' lines using CCP module.
Then it displays childrens indented multiple times for each element of crypto_map variable (list).

'''
import pprint
from ciscoconfparse import CiscoConfParse

file = open('cisco.txt', 'r')  # Opening text file wiht open() function
parse = CiscoConfParse(
    file)  # Loading the file to CCF module as argument for parsing later
crypto_map = parse.find_all_children(
    r'^crypto map CRYPTO'
)  # Using find_all_children method with regex (parsing)

print 'Show the content of crypto_map variable: \n', crypto_map
print

print 'Show me parent-child relationships for crypto map CRYPTO lines in cisco.txt file: '
# Iterate over elements of crypto_map list and display in a nice human readable format
for line in crypto_map:
    pprint.pprint(line)
quit()
#!/usr/bin/env pytho
'''
This script parses cisco.txt file and searches for 'crypto map CRYPTO' lines using CCP module.
Then it displays childrens indented multiple times for each element of crypto_map variable (list).

'''
import pprint
from ciscoconfparse import CiscoConfParse

file = open('cisco.txt', 'r')        # Opening text file wiht open() function
parse = CiscoConfParse(file)         # Loading the file to CCF module as argument for parsing later
crypto_map = parse.find_all_children(r'^crypto map CRYPTO')       # Using find_all_children method with regex (parsing)

print 'Show the content of crypto_map variable: \n',crypto_map
print

print 'Show me parent-child relationships for crypto map CRYPTO lines in cisco.txt file: '
# Iterate over elements of crypto_map list and display in a nice human readable format
for line in crypto_map:
    pprint.pprint(line)
quit()