Using textFSM to parse multiple show commands

748 views Asked by At

I'm trying to use textFSM to compile some Juniper "show" command outputs and get specific fields from them and finally printing collected info in one run. This is my code:

import textfsm
import getpass
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
import os

def enable_netconf(remote_device):
    junos_device = ConnectHandler(**remote_device)
    command_2 = junos_device.send_command("show interfaces")
    junos_device.disconnect()

def main():
    print("Enter Device info to check:\n")
    tuser = input("Enter username: ")
    tpw = getpass.getpass()
    with open("D:\Documents\sample3.csv", encoding='utf-8') as tf:
        for line in tf:
            my_ip = line.rstrip(os.linesep)
            remote_device = {
                'device_type': 'juniper',
                'ip': my_ip,
                'username': tuser,
                'password': tpw,
            }
            enable_netconf(remote_device)
    with open("D:\Documents\juniper_junos_show_interfaces.textsm", "r") as f:
        template = textfsm.TextFSM(f)
        result = template.ParseText(command_2)
    print(result)
    
if __name__ == '__main__':
    main()

I used Netmiko to connect to Juniper vMX device. I also download textFSM "show interfaces" temple from this link (https://github.com/networktocode/ntc-templates/blob/master/ntc_templates/templates/juniper_junos_show_interfaces.textfsm) and saved them in D:\Documents folder.

first of All I need to make the basic function of textFSM to work. in the above code I got the error saying that "command_2" variable has not been defined which as seen I defined it inside the "def enable_netconf(remote_device)".

Would you please help me on this as I'm a newbie in Python. Thanks.

1

There are 1 answers

0
Mert Kulac On

If you want to use a variable in a different def, you can use the global command. In this example, just put "global comman_2" just below def enable_netconf(remote_device):

def enable_netconf(remote_device):

global command_2
junos_device = ConnectHandler(**remote_device)
command_2 = junos_device.send_command("show interfaces")
junos_device.disconnect()