def main(cisco_file='cisco_ipsec.txt'): ''' Using ciscoconfparse find the crypto maps that are not using AES (based-on the transform set name). Print these entries and their corresponding transform set name. ''' cisco_cfg = CiscoConfParse(cisco_file) for crypto_map in cisco_cfg.find_objects_wo_child( parentspec=r'crypto map CRYPTO', childspec=r'AES'): for child in crypto_map.children: if 'transform' in child.text: match = re.search(r"set transform-set (.*)$", child.text) print "{0} : {1}".format(crypto_map.text.strip(), match.group(1))
def main(): ''' Find all of the crypto map entries in the file (lines that begin with 'crypto map CRYPTO') and print out the children of each crypto map. ''' cisco_file = 'cisco_ipsec.txt' cisco_cfg = CiscoConfParse(cisco_file) crypto_maps = cisco_cfg.find_objects(r"^crypto map CRYPTO") for c_map in crypto_maps: print print c_map.text for child in c_map.children: print child.text print
def confCheck(): with open('tempfile.txt', 'r') as f: conf = f.readlines() parse = CiscoConfParse(conf) running_qos = '' qos_list = [] device_name = (parse.find_objects("^hostname")[0].text) try: running_qos = (parse.find_objects("^policy-map SHAPE-")) # running_qos = (parse.find_objects("^policy-map SHAPE-")[0].text) except: pass return [device_name.split()[1], running_qos]
def main(): ''' Using ciscoconfparse find the crypto maps that are not using AES (based-on th transform set name). Print these entries and thier correspinding transfo rm set name. ''' cisco_file = ('cisco_ipsec.txt') cisco_cfg = CiscoConfParse(cisco_file) crypto_maps = cisco_cfg.find_objects_wo_child(parentspec=r'crypto map CRYPTO', childspec=r'AES') print "\nCrypto Maps not using AES:" for entry in crypto_maps: for child in entry.children: if 'transform' in child.text: match = re.search(r"set transform-set (.*)$", child.text) encryption = match.group(1) print " {0} >>> {1}".format(entry.text.strip(), encryption) print
def check_routing_protocol_enabled_and_used( config: typing.List[str], ) -> typing.Optional[CheckResult]: """Check if a routing protocol is actually used - should it be enabled.""" parsed_config = CiscoConfParse(config) for protocol in ["bgp", "ospf", "eigrp", "rip"]: feature_enabled = parsed_config.find_lines(f"^feature {protocol}") if not feature_enabled: return None feature_used = parsed_config.find_lines(f"^router {protocol}") if not feature_used: return CheckResult( text=f"{protocol.upper()} enabled but never used.", lines=feature_enabled + feature_used, ) return None
def get_result(self, config): ''' Returns a boolean result after running the defined test on the passed configuration :configuration: a configuration object as defined in netaudit.config ''' contents = config.contents result = False message = '' if self.type == 'config' or isinstance(self.pattern, list): has_failure = False # Track if there is an explicit failure parse = CiscoConfParse(re.split('(?:\r\n|\n|\r)', contents)) patterns = self.pattern parents = parse.find_objects(patterns[0]) for i in range(1, len(patterns)): children = [] for parent in parents: if i >= len(patterns) - 1: match = parent.re_match_iter_typed(patterns[i], default=None) if match and match == self.expected: result = True else: has_failure = True message += ( "Match failed for configuration, line %r.\n" % (parent.linenum)) else: match = parent.re_search_children(patterns[i]) if match: children.extend(match) else: has_failure = True message += ("Could not find child, line %r.\n" % (parent.linenum)) parents = children result = (not has_failure) & result elif self.type == 'text' or self.type is None: for line in contents.split('\n'): #print ('%s, %s, %s' % (test.pattern, test.expected, line)) match = re.search(self.pattern, line) if match is not None and match.group(1) == self.expected: result = True self._last_message = message if message != '' else None return result
def parse(file_name): f = open(file_name, "r") cisco_cfg = CiscoConfParse(f.read().splitlines(keepends=False)) interfaces = cisco_cfg.find_objects_w_child(parentspec=r"^interface", childspec=r"^\s+ip address") # print(interfaces) for i in interfaces: # print("Interface: {}".format(i.text)) ip_address = i.re_search_children(r"ip address")[0].text description_list = i.re_search_children(r"description") if len(description_list) == 0: # HAS DESCRIPTION continue description = description_list[0].text # parts = description.split("-") # user = parts[-1] if not description.endswith("USER"): continue authentication_list = i.re_search_children(r"authentication") if len(authentication_list ) == 1 and authentication_list[0].text == "port-control auto": continue good_count = 0 if len(authentication_list) > 0: bad = False for a in authentication_list: if a.text == " authentication open": bad = True elif a.text == " authentication port-control auto": good_count += 1 if bad == False: continue if good_count > 0 and not bad: continue #BAD print("Interface: {}".format(i.text)) print("IP Address: {}".format(ip_address)) print() print()
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)
def main(): cisco_cfg_file = "cisco_ipsec.txt" cisco_cfg = CiscoConfParse(cisco_cfg_file) crypto_not_aes = cisco_cfg.find_objects_wo_child( parentspec=r"crypto map CRYPTO", childspec=r"AES") print("Crypto Maps not using AES:") for c_map in crypto_not_aes: #print(" {0}").format(c_map.text) for child in c_map.children: #print (" {0}").format(child.text) if "transform" in child.text: match = re.search(r"set transform-set (.*)$", child.text) encryption = match.group(1) print(" {0} >>> {1}".format(c_map.text.strip(), encryption)) print
def testValues_sync_diff_04(): """Test diffs against double-spacing for children (such as NXOS)""" ## config_01 is the starting point config_01 = [ '!', 'interface GigabitEthernet 1/5', ' ip address 1.1.1.2 255.255.255.0', ' standby 5 ip 1.1.1.1', ' standby 5 preempt', '!' ] required_config = [ '!', 'interface GigabitEthernet 1/5', ' switchport', ' switchport mode access', ' switchport access vlan 5', ' switchport nonegotiate', '!', 'interface Vlan5', ' no shutdown', ' ip address 1.1.1.2 255.255.255.0', ' standby 5 ip 1.1.1.1', ' standby 5 preempt', '!', ] result_correct = [ 'interface GigabitEthernet 1/5', ' no ip address 1.1.1.2 255.255.255.0', ' no standby 5 ip 1.1.1.1', ' no standby 5 preempt', 'interface GigabitEthernet 1/5', ' switchport', ' switchport mode access', ' switchport access vlan 5', ' switchport nonegotiate', 'interface Vlan5', ' no shutdown', ' ip address 1.1.1.2 255.255.255.0', ' standby 5 ip 1.1.1.1', ' standby 5 preempt', ] linespec = r'' parse = CiscoConfParse(config_01) test_result = parse.sync_diff(required_config, linespec, linespec) assert result_correct == test_result
def build_interface(self): if self._device.config: config_exporter = DeviceConfigExporter(self._device.config, 'interface') parse = CiscoConfParse(self._device.config.splitlines()) # Return a list of all interfaces interface_cmds = parse.find_objects('^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) interface_name = interface_cmd.text[len('interface\s'):] interface_desc = 'not set' for cmd in interface_cmd.re_search_children( r'^\sdescription\s'): interface_desc = cmd.text.strip()[len('description\s'):] interface_encap = 'not set' for cmd in interface_cmd.re_search_children( r'^\sencapsulation\s'): interface_encap = cmd.text.strip()[len('encapsulation\s'):] interface_rewrite = 'not set' for cmd in interface_cmd.re_search_children(r'^\srewrite\s'): interface_rewrite = cmd.text.strip()[len('rewrite\s'):] interface_serv_policies = { 'input': 'not set', 'output': 'not set' } for cmd in interface_cmd.re_search_children( r'^\sservice-policy\sinput\s'): interface_serv_policies['input'] = cmd.text.strip( )[len('service-policy\sinput\s'):] # output command for cmd in interface_cmd.re_search_children( r'^\sservice-policy\soutput\s'): interface_serv_policies['output'] = cmd.text.strip( )[len('service-policy output\s'):] self._device.connect(NetInterface(name=interface_name))
def testValues_banner_delimiter_05(): # Test multiple banners CONFIG = ['!', 'banner motd ^', ' trivial banner1 here ^', 'banner exec ^', ' trivial banner2 here ^', 'end'] parse = CiscoConfParse(CONFIG) bannerobj = parse.find_objects('^banner\smotd')[0] BANNER_LINE_NUMBER = 1 assert bannerobj.linenum == BANNER_LINE_NUMBER for obj in bannerobj.children: assert obj.parent.linenum == BANNER_LINE_NUMBER bannerobj = parse.find_objects('^banner\sexec')[0] BANNER_LINE_NUMBER = 3 assert bannerobj.linenum == BANNER_LINE_NUMBER for obj in bannerobj.children: assert obj.parent.linenum == BANNER_LINE_NUMBER
def testVal_parse_F5(): """Test for Github issue #49""" config = [ 'ltm virtual virtual1 {', ' profiles {', ' test1 { }', ' }', '}', 'ltm virtual virtual2 {', ' profiles2 {', ' test2 { }', ' }', '}', ] parse = CiscoConfParse(config, syntax='junos') retval = parse.find_objects('profiles2')[0].children assert retval[0].text == ' test2 '
def main(): """ Use the ciscoconfparse library to find the crypto maps that are using pfs group2 """ cisco_file = 'cisco_ipsec.txt' cisco_cfg = CiscoConfParse(cisco_file) crypto_maps = cisco_cfg.find_objects_w_child( parentspec=r'crypto map CRYPTO', childspec=r'pfs group2') printout(crypto_maps) print("\nCrypto Maps using PFS group2:") for entry in crypto_maps: print(" {}".format(entry.text)) print("\n")
def testVal_ipv4_standby_addr(self): conf = [ '!', 'interface Ethernet0/0', ' nameif OUTSIDE', ' ip address 198.101.172.106 255.255.255.128 standby 198.101.172.107', '!', 'interface Ethernet0/1', ' nameif INSIDE', ' ip address 192.0.2.254 255.255.255.0', '!', ] cfg_factory = CiscoConfParse(conf, factory=True, syntax='asa') obj = cfg_factory.find_objects(r'^interface\sEthernet0\/0$')[0] # Ensure obj.ipv4_standby_addr is set correctly self.assertEqual(obj.ipv4_standby_addr, '198.101.172.107')
def remove_config_blocks(run_config): parse = CiscoConfParse(run_config) # delete exiting configuration that needs to be replaced for obj in parse.find_objects(r"^interface"): obj.delete() for obj in parse.find_objects(r"boot system"): obj.delete() # commit modifications to the current parse object parse.commit() #return IOS formated config to be used in script return '\n'.join(parse.ioscfg) # use below parse command if file needs to be saved locally # parse.save_as('modified_startup')
def get_the_static_route_config(vrf_name, far_end_ip): parse_9k = CiscoConfParse( 'phase3-BLR-MPL-PE-RTR-188_Running_Config_28-DEC-2016.iox') next_hop = parse_9k.find_objects(r'/[0-9]+\s+' + far_end_ip) for k1 in next_hop: config = '' next_hop_parent = k1.parent '''next_hop_parent will be something like 'address-family ipv4 unicast''' if 'address-family ipv4 unicast' in next_hop_parent.text: if vrf: parent_of_next_hop_parent = next_hop_parent.parent '''the above should have vrf name ''' parent_of_parent_of_next_hop_parent = parent_of_next_hop_parent.parent #print parent_of_parent_of_next_hop_parent.text #the above will be router static #print parent_of_next_hop_parent.text #the above will be vrf name if 'vrf ' + vrf_name in parent_of_next_hop_parent.text and 'router static' in parent_of_parent_of_next_hop_parent.text: print 'hi' config += '\n' + parent_of_parent_of_next_hop_parent.text + '\n' + parent_of_next_hop_parent.text + '\n' + next_hop_parent.text for k2 in next_hop_parent.children: chk = re.search(r"\b" + re.escape(far_end_ip) + r"\b", k2.text) if chk: config += '\n' + k2.text print config break if not vrf: parent_of_next_hop_parent = next_hop_parent.parent '''the above should have router static ''' #print parent_of_next_hop_parent.text #the above will be vrf name if 'router static' in parent_of_next_hop_parent.text: print 'hi' config += '\n' + parent_of_next_hop_parent.text + '\n' + next_hop_parent.text for k2 in next_hop_parent.children: chk = re.search(r"\b" + re.escape(far_end_ip) + r"\b", k2.text) if chk: config += '\n' + k2.text print config break
def main(): cisco_file = 'cisco_ipsec.txt' cisco_cfg = CiscoConfParse(cisco_file) crypto_maps = cisco_cfg.find_objects_wo_child( parentspec=r'crypto map CRYPTO', childspec=r'AES') print("\nCrypto maps not using AES:") for entry in crypto_maps: for child in entry.children: if 'transform' in child.text: match = re.search(r"set transform-set (.*)$", child.text) encryption = match.group(1) print(" {} >>> {}".format(entry.text.strip(), encryption)) print()
def Cisco_Parser(filename): cisco_cfg=CiscoConfParse(filename) interfaces=cisco_cfg.find_objects(r"^interface") vtys=cisco_cfg.find_objects(r"^line vty ") for intf in interfaces: output= str(intf) output+= '\n' + str(intf.children) for vty in vtys: output+= '\n' + '#' * 80 output+= "Configuration for Line vty is: \n {}".format(vty.children) l2_interfaces=cisco_cfg.find_objects_w_child(parentspec=r"^interface", childspec="no ip address") l3_interfaces=cisco_cfg.find_objects_wo_child(parentspec=r"^interface", childspec="no ip address") output+= '\n' +'#' * 80 output+= "\nL2 Interfaces are {}".format(l2_interfaces) output+= '\n' +'#' * 80 output+= "\nL3 Interfaces are {}".format(l3_interfaces) return output
def index(request): # net_connect = ConnectHandler(device_type='cisco_ios', ip='ip_address', username='******', password='******') # net_connect.find_prompt() # output = net_connect.send_command("show run") # tidak bisa tes koneksi langsung karena ssh cisco tidak bisa di open "connection refused" # contoh config langsung parse = CiscoConfParse("media/contoh.txt") #open file di folder media # contoh output parse interfaces active_intfs = parse.find_parents_wo_child("^interf", "shutdown") jso = json.dumps([dict(interfaces=inter) for inter in active_intfs]) with open('media/output.json', 'w') as f: f.write(json.dumps( jso, indent=4)) #membuat nama file di folder media namanya output.json return render(request, "index.html", {"parse": active_intfs, "json": jso})
def update_device_loopback_conf(self): """ Updates the Loopback interfaces configuration for nodes in the lab topology. For each node it will call the platform specific method to update Loopback interface address from provided subnet using the next available address for each device. """ ip = netaddr.IPNetwork(self._cmlnetkitconfig.loopback_subnet) try: for nodenum, nodedef in enumerate(self.lab_conf["nodes"]): # We find the method to call using the self._node_types_fm dictionary try: node_config = self._get_node_config( self._get_node_index_by_label(nodedef.get("label"))) node_parsed_config = CiscoConfParse( node_config.split('\n')) self._node_types_fn["update_node_loopback_conf_" + self._get_node_type( self._get_node_index_by_label( nodedef.get("label")))]( node_parsed_config, ip[nodenum + 1].__str__()) node_parsed_config.atomic() node_new_config = '\n'.join( [i for i in node_parsed_config.ioscfg[0:]]) self._set_node_config( self._get_node_index_by_label(nodedef.get("label")), node_new_config) self.lab_conf_changed = True except TypeError as e: raise TypeError(e) # No key found in self._node_types_fn except KeyError as e: # For other than known and specified in self._node_types_fn node types do nothing just ignore continue # raise KeyError(e) # Exception from CiscoConfParse constructor except ValueError as e: raise ValueError(e) except IndexError as e: raise IndexError( "lo-subnet: Not enough loopback addresses provided")
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)
def main(): ''' Find all of the crypto map entries in the file (lines that begin with 'crypto map CRYPTO')and print out the children of each crypto map. ''' # define the file you wish to parse and make it a callable object cisco_file = '/Users/mstrocchia/Python_Training/Python4Network/GIT/pynet/pyth_ans_ecourse/class1/cisco_ipsec.txt' # define an object that uses ciscoconfparse() then pass it the file object cisco_cfg = CiscoConfParse(cisco_file) # define an objct that appends the .find_objects function to your ciscoconfparse object and give it search criteria crypto_maps = cisco_cfg.find_objects("^crypto map CRYPTO") for c_map in crypto_maps: # for each list element in your output print it in text print print c_map.text for child in c_map.children: # For each child associated wiht a parent found in cmap, append the .children fucntion to grab the child data print child.text # print the parent and child data in readable text print
def parse_config(device_file_name): """Locate the config for ``device_name`` in the ['audits']['config_dir'] directory, then parse the configuration and store in the DEVICE_CONFIGS dictionary. """ path = os.path.expanduser(os.path.join( TESTCONFIG['audits']['config_dir'], device_file_name)) if not os.path.exists(path): pytest.fail('{0} is not a valid config'.format(path)) # if not DEVICE_CONFIGS.get(path, False): DEVICE_CONFIGS[path] = CiscoConfParse( config=path, ignore_blank_lines=False, ) return DEVICE_CONFIGS[path]
def connect(self): import paramiko import time cisco_dev = { 'device_type': self.dev_type, 'ip': self.mgmt_ip, 'username': self.username, 'password': self.password, 'port': 22, # optional, defaults to 22 'secret': 'secret', # optional, defaults to '' 'verbose': False, # optional, defaults to False } self.net_connect = ConnectHandler(**cisco_dev) self.ssh_output = self.net_connect.send_command("show run") #self.config = self.ssh_output self.parsed_config = CiscoConfParse(self.ssh_output.split()) self.status = True
def findEthPort(socket, *last_config): ''' parse Cisco config and return interfaces list ''' # extract from tupel -> list last_config = last_config[0] ports = [] # run for path in last_config: parse = CiscoConfParse(path) switch = path.split("/") serial_objs = parse.find_blocks("description "+socket) if serial_objs: ports.append('<h4>Switch: ' + switch[3] + '</h4>') for obj in serial_objs: ports.append(obj) serial_objs = [] return ports
def pog_cd(filename): pog_all = {} mycfg = CiscoConfParse(filename) lines = mycfg.find_objects(r'^object-group protocol') if lines != []: for parent_item in lines: list_child_items = [] for child_item in parent_item.all_children: list_child_items.append(child_item.text) pog_all[parent_item.text] = list_child_items lines = mycfg.find_objects(r'^object protocol') if lines != []: for parent_item in lines: list_child_items = [] for child_item in parent_item.all_children: list_child_items.append(child_item.text) pog_all[parent_item.text] = list_child_items return pog_all
def testVal_object_group_service_02(): ## This can only be configured as an object group after a host / network conf = ['!', 'object-group service APP02_svc tcp', ' port-object eq smtp', ' port-object eq https', ' port-object range 8080 8081', '!',] cfg_factory = CiscoConfParse(conf, factory=True, syntax='asa') obj = cfg_factory.find_objects(r'object-group\sservice')[0] result_correct = [L4Object(protocol='tcp', port_spec='eq 25', syntax='asa'), L4Object(protocol='tcp', port_spec='eq 443', syntax='asa'), L4Object(protocol='tcp', port_spec='range 8080 8081', syntax='asa')] assert (obj.name=='APP02_svc') assert (obj.ports==result_correct) assert (obj.L4Objects_are_directional is False) assert (obj.protocol_type=='tcp')
def cisco_conf_parse_objects(cfg_section, config): """ Use CiscoConfParse to find and return a section of Cisco IOS config. Similar to "show run | section <cfg_section>" :param cfg_section: The section of the config to return eg. "router bgp" :param config: The running/startup config of the device to parse """ return_config = [] if type(config) is str: config = config.splitlines() parse = CiscoConfParse(config) cfg_obj = parse.find_objects(cfg_section) for parent in cfg_obj: return_config.append(parent.text) for child in parent.all_children: return_config.append(child.text) return return_config
def main(): #YAML file cisco_cfg = CiscoConfParse("./cisco_file.txt") crypto_sections = cisco_cfg.find_objects(r"^crypto map CRYPTO") #print 'Len of crypto_sections is', len(crypto_sections) for item in crypto_sections: print item.children print '\n' for index in range(0, len(crypto_sections)): print crypto_sections[index].text for item in crypto_sections[index].all_children: print item.text print '\n'