mpenning / ciscoconfparse

Parse, Audit, Query, Build, and Modify Arista / Cisco / Juniper / Palo Alto / F5 configurations.
http://www.pennington.net/py/ciscoconfparse/
GNU General Public License v3.0
789 stars 219 forks source link

how do i get the output of parse in a readable format such as text, so that i can use it to iterate using a for loop #146

Closed sagarh9 closed 5 years ago

sagarh9 commented 5 years ago

Below is my code:

!/usr/bin/env python

from ciscoconfparse import CiscoConfParse from getpass import getpass from netmiko import ConnectHandler

import netmiko import json import time

devices = ''' 192.168.122.71 '''.strip().splitlines()

device_type = 'cisco_ios' username = 'sagar' password = getpass()

for ip in devices: print('-'*79) print('Connecting to device',ip) connection = netmiko.ConnectHandler(ip=ip, device_type=device_type, username=username, password=password, secret=password) connection.enable() print(connection.find_prompt()) running = connection.send_command('show run') connection.config_mode() parse = CiscoConfParse(running.splitlines()) output = parse.find_objects_wo_child(r'^interface\sGig', r'shutdown')

for line in output:
    print(line.text)
    connection.find_prompt()
    connection.send_command_timing(line.text)
    connection.send_command_timing('flowcontrol send desired')
    connection.send_command_timing('exit')
    print('done', line.text)

because line.text has the value [u'interface GigabitEthernet0/0'] and this value is not recognized by the Cisco device. How to get only [interface GigabitEthernet0/0] to use it to iterate over?

Output of the code:


Password:
-------------------------------------------------------------------------------
('Connecting to device', '192.168.122.71')
Sw1#
interface GigabitEthernet0/0
('done', u'interface GigabitEthernet0/0')
interface GigabitEthernet0/1
('done', u'interface GigabitEthernet0/1')
interface GigabitEthernet0/2
('done', u'interface GigabitEthernet0/2')```
mpenning commented 5 years ago

if "line" is a CiscoConfParse object, then "line.text" is the text line that Cisco IOS understands.

u'foo' simply means that you've got a unicode string.

sagarh9 commented 5 years ago

But if you see the last line of the for loop "print('done', line.text)", i have specified the text line to be printed, but instead i get the output: ('done', u'interface GigabitEthernet0/2')```

Why is that?

mpenning commented 5 years ago

Why is that?

That's what you asked Python to do... observe the differences in the two print statements below...

 % python

Python 2.7.2 (default, Nov 23 2011, 14:16:03)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print("foo")
foo
>>> print("foo", "bar")
('foo', 'bar')
>>>