Exemple #1
0
def validateconfigLAN(devconfig):
    parse = CiscoConfParse(io.StringIO(devconfig), syntax='ios')
    intf_hostname = parse.re_match_iter_typed(r'^hostname\s+(\S+)', default='')
    interfaces = []

    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_policy = intf_obj.re_match_iter_typed(
            r'service-policy\sinput\s(\w+\-\w+\-\w+)\s',
            result_type=str,
            group=1,
            default='')
        if intf_policy:
            interfaces.append(intf_name)
            writefile = intf_hostname + '\t' + intf_name + '\t' + intf_policy
            with open('C:\\scripts_logs\\QoS2\\LAN\\' + username + '.log',
                      'a') as f:
                f.write(writefile)
                f.write('\n')

    return [intf_hostname, interfaces]
Exemple #2
0
 def _get_all_vlans_entries(self):
     self.__logger.info("Get Info Vlans")
     parse = CiscoConfParse(self.file_input)
     self.hostname = parse.re_match_iter_typed(r'^hostname\s+(\S+)',
                                               default='None')
     self.__logger.info(f"Hostname: {self.hostname}")
     for obj in parse.find_objects(r'^vlan\s*\d+'):
         if re.search(r'[,-]', obj.text):
             lst = obj.text.split()[1]
             for vl in lst.split(','):
                 if vl.isdigit():
                     cisco = Vlan(self.__dbg)
                     cisco.get_all_properties(f'vlan {vl}')
                     self.vlan_entries.append(cisco)
                 else:
                     (ib, ie) = list(vl.strip().split('-'))
                     for jj in range(int(ib), int(ie) + 1):
                         cisco = Vlan()
                         cisco.get_all_properties(f'vlan {jj}')
                         self.vlan_entries.append(cisco)
         else:
             cisco = Vlan(self.__dbg)
             cisco.get_all_properties(obj.text)
             for obj_child in obj.children:
                 cisco.get_all_properties(obj_child.text)
             self.vlan_entries.append(cisco)
             self.__logger.debug(f"L2 int: {cisco.name}")
Exemple #3
0
 def _get_all_l3_int_entries(self):
     parse = CiscoConfParse(self.file_input)
     self.hostname = parse.re_match_iter_typed(r'^hostname\s+(\S+)',
                                               default='None')
     for obj in parse.find_objects_w_child(r'^interface',
                                           r'^\s*ip address'):
         cisco = L3Interface()
         cisco.get_all_properties(obj.text)
         for obj_child in obj.children:
             cisco.get_all_properties(obj_child.text)
         self.l3_int_entries.append(cisco)
Exemple #4
0
 def _get_all_l2_int_entries(self):
     self.__logger.info("Get Info L2 interfaces")
     parse = CiscoConfParse(self.file_input)
     self.hostname = parse.re_match_iter_typed(r'^hostname\s+(\S+)',
                                               default='None')
     self.__logger.info(f"Hostname: {self.hostname}")
     for obj in parse.find_objects_wo_child(r'^interface',
                                            r'^\s*(no)?\s*ip address'):
         cisco = L2Interface(self.__dbg)
         cisco.get_all_properties(obj.text)
         for obj_child in obj.children:
             cisco.get_all_properties(obj_child.text)
         self.l2_int_entries.append(cisco)
         self.__logger.debug(f"L2 int: {cisco.name}")
def Get_Conf():
    parse = CiscoConfParse('conf.txt')

    #ホスト名の値だけ取得したい
    global_obj = parse.find_objects(r'^hostname')[0]
    print(global_obj)
    hostname = global_obj.re_match_typed(r'^hostname\s+(\S+)', default='')
    print(hostname)

    #反復処理して見つかった最初の値を返す
    hostname = parse.re_match_iter_typed(r'^hostname\s+(\S+)', default='')
    print(hostname)

    #VLAN10のHSRP IPアドレスを取得
    intf_obj = parse.find_objects(r'^interface\s+Vlan10$')[0]
    hsrp_ip = intf_obj.re_match_iter_typed(r'standby\s10\sip\s(\S+)',
                                           default='')
    print(hsrp_ip)

    #VLAN10のARPタイムアウト値を取得(intで返す)
    intf_obj = parse.find_objects(r'^interface\s+Vlan10$')[0]
    arp_timeout = intf_obj.re_match_iter_typed(r'arp\s+timeout\s+(\d+)',
                                               result_type=int,
                                               default=4 * 3600)
    print(arp_timeout)

    #要素が見つからなかった場合のデフォルト値の指定
    intf_obj = parse.find_objects(r'^interface\s+Vlan20$')[0]
    arp_timeout = intf_obj.re_match_iter_typed(r'arp\s+timeout\s+(\d+)',
                                               result_type=int,
                                               untyped_default=True,
                                               default='__no_explicit_value__')
    print(arp_timeout)

    retval = list()
    HELPER_REGEX = r'ip\s+helper-address\s+(\S+)$'
    NO_MATCH = '__no_match__'

    #VLAN10のDHCPヘルパーアドレス(複数)を返す処理
    for intf_obj in parse.find_objects(r'^interface\s+Vlan10$'):
        for child_obj in intf_obj.children:  # Iterate over intf children
            val = child_obj.re_match_typed(HELPER_REGEX, default=NO_MATCH)
            if val != NO_MATCH:
                retval.append(val)

    print(retval)
Exemple #6
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
    ]
import os
from ciscoconfparse import CiscoConfParse

# Set config directories for existing and new output
dir = 'configs'
changes = 'nac-configs'

# Iterate through each file in the config directory
for filename in os.listdir('configs'):
    file = 'configs/' + filename
    outFile = open(changes + '/' + filename + '.delta', 'w')
    # Parse the config file into objects
    parse = CiscoConfParse(file, syntax='ios')
    interfaces = []

    SWversion = parse.re_match_iter_typed(r'^version\s(\S+)',
                                          default='no version')
    #print('SW Version: ' + SWversion)

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

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

        if (has_switchport_access or has_shutdown) and not has_netdescript:
            interfaces.append(intf_obj.text)
            intf_obj.append_to_family(
                ' description **This Port Has Been NAC Enabled**')
Exemple #8
0
#!/usr/bin/python3

from typing import Text
from ciscoconfparse import CiscoConfParse

with open("RAC_BNTWP21C.conf", 'r') as f:
    parse = CiscoConfParse(f.readlines(), syntax='ios')
    '''Get host name'''
    hostname = parse.re_match_iter_typed(r'^hostname\s+(\S+)', default='')
    print("Router hoostname :" + hostname + "\n")
    '''List all interfaces with child'''
    #print(parse.find_objects('^interface')[0].children[1])
    for intf_obj in parse.find_objects('^interface')[0:2]:
        print("ciscoconfparse object : " + str(intf_obj))
        '''for c_obj in intf_obj.children:
            print("Child obj :" + str(c_obj))'''
    '''List shutdown interfaces'''
    for intf_obj in parse.find_objects_w_child('^interface', '^\s+shutdown'):
        print("Shutdown: " + intf_obj.text)
Exemple #9
0
'hostname,\
interface,\
description, \
ip_addr, \
network, \
prefix_length, \
shutdown, \
acl_in, \
acl_out'        )

for pfile in pdirectory:

    parse = CiscoConfParse(pfile)

    #variable
    hostname = parse.re_match_iter_typed(RE_HOSTNAME)

    for obj in parse.find_objects_w_child(parentspec=RE_INTF_PARENT,
                                          childspec=RE_INTF_CHILDSPEC):

        #print('Config test: {} '.format(obj.text))

        #intf = obj.re_match_iter_typed(RE_INTF_PARENT)
        try:
            ip_addr = obj.re_match_iter_typed(RE_ITF_ADDR, result_type=IPv4Obj)
            itf_des = obj.re_match_iter_typed(RE_ITF_DES)
            itf_acl_in = obj.re_match_iter_typed(RE_ITF_ACL_IN)
            itf_acl_out = obj.re_match_iter_typed(RE_ITF_ACL_OUT)
            itf_shut = obj.re_match_iter_typed(RE_ITF_SHUT)
            if itf_shut:
                itf_shut = 'shutdown'