def textfsm_parse_to_dict(input_data, template_filename): """ Use TextFSM to parse the input text (from a command output) against the specified TextFSM template. Convert each list from the output to a dictionary, where each key in the TextFSM Value name from the template file. :param input_data: Path to the input file that TextFSM will parse. :param template_filename: Path to the template file that will be used to parse the above data. :return: A list, with each entry being a dictionary that maps TextFSM variable name to corresponding value. """ logger.debug( "Preparing to process with TextFSM and return a list of dictionaries.") # Create file object to the TextFSM template and create TextFSM object. logger.debug("Using template at: {0}".format(template_filename)) with open(template_filename, 'r') as template: fsm_table = textfsm.TextFSM(template) # Process our raw data vs the template with TextFSM fsm_list = fsm_table.ParseText(input_data) logger.debug("TextFSM returned a list of size: '{0}'".format( len(fsm_list))) # Insert a header row into the list, so that when output to a CSV there is a header row. header_list = fsm_table.header # Combine the header row with each entry in fsm_list to create a dictionary representation. Add to output list. output = [] for entry in fsm_list: dict_entry = dict(zip(header_list, entry)) output.append(dict_entry) logger.debug("Converted all sub-lists to dicts. Size is {0}".format( len(output))) return output
def textfsm_parse_to_list(input_data, template_name, add_header=False): """ Use TextFSM to parse the input text (from a command output) against the specified TextFSM template. Use the default TextFSM output which is a list, with each entry of the list being a list with the values parsed. Use add_header=True if the header row with value names should be prepended to the start of the list. :param input_data: Path to the input file that TextFSM will parse. :param template_name: Path to the template file that will be used to parse the above data. :param add_header: When True, will return a header row in the list. This is useful for directly outputting to CSV. :return: The TextFSM output (A list with each entry being a list of values parsed from the input) """ logger.debug( "Preparing to process with TextFSM and return a list of lists") # Create file object to the TextFSM template and create TextFSM object. logger.debug("Using template at: {0}".format(template_name)) with open(template_name, 'r') as template: fsm_table = textfsm.TextFSM(template) # Process our raw data vs the template with TextFSM output = fsm_table.ParseText(input_data) logger.debug("TextFSM returned a list of size: '{0}'".format(len(output))) # Insert a header row into the list, so that when output to a CSV there is a header row. if add_header: logger.debug("'Adding header '{0}' to start of output list.".format( fsm_table.header)) output.insert(0, fsm_table.header) return output