Simplicity is the ultimate sophistication

Font Size




Python & Net Prog.

Looking ahead when using TextFSM to extract information from text

TextFSM is a very useful Python module that can be used to extract information from a text and store the information in a tabular structure (table/spreadsheet etc)

The idea behind the TextFM is to create a template for each specific text you need to process (output of command) and to use that template to extract the information. You will define the column using the keyword “Value” in your template and then you will create rules to process each line.

There is a particular situation like below when you want to save all data collected from the lines between two similar lines (the lines containing the word “interface” in our case). I could not figure out other way to look ahead other than the below. The trick is suggested by the author of the module in his example of using lists. In our case we do not want lists but we just want to look ahead ….

interface Loopback1
interface Eth1/1
  speed 100
  duplex full
interface Eth1/2
  duplex full
interface Eth1/3
  speed 100

Your template could look like below

Value Required Interface (\S+)
Value Speed (\d+)
Value Duplex (full)

# the below line will not save the record at
# the first hit because $Interface=''
# the second time the rule is hit (when we reach
# the next interface) it will save the already collected record) ^interface ->Continue.Record ^\s+speed ${Speed} ^\s+duplex ${Duplex} ^\interface ${Interface}

so you are saving the record only after looking forward for each interface line, processing the config lines and save when you hit the next "interface” line.

This is an important trick because that is the only way to look ahead... as far as I can tell (might be wrong I am just started using this)

    Python -useful links

    Image result for python iconI mostly use Python for Windows. Here are a couple of links that I always end up using in order to solve problems related to intalling Python packages under Windows.

    Most of the libraries that I have had to use are either not updated to the latest Python version or they require compiling from source which brings in another problem: you need the use the right compiler. So here are the links:

    Home Python & Net Prog.