1

I'm trying to convert the cisco running configuration into parameters using python, and i'm stuck at reading configuration sections with python. Say for instance you have the below stanza:

!
interface Async1
 no ip address
 encapsulation slip
!       
router bgp 65500
 bgp router-id 1.1.1.1
 bgp log-neighbor-changes
 timers bgp 10 30
 neighbor 1.2.3.4 remote-as 1234
 neighbor 1.2.3.4 description Some Description
 neighbor 1.2.3.4 update-source GigabitEthernet0/0
 !
 address-family ipv4
  network 2.2.2.2 mask 255.255.255.255
  network 3.3.3.0 mask 255.255.255.252
  neighbor 1.2.3.4 activate
  neighbor 1.2.3.4 allowas-in 3
  neighbor 1.2.3.4 prefix-list PXL out
 exit-address-family
!
ip forward-protocol nd
no ip http server
no ip http secure-server
!

I want to read lines from 'router bgp' until first line that starts with '!' (e.g ^!), and then re-read the block to extract parameters into variables. A sample output would be:

router bgp 65500
 bgp router-id 1.1.1.1
 bgp log-neighbor-changes
 timers bgp 10 30
 neighbor 1.2.3.4 remote-as 1234
 neighbor 1.2.3.4 description Some Description
 neighbor 1.2.3.4 update-source GigabitEthernet0/0
 !
 address-family ipv4
  network 2.2.2.2 mask 255.255.255.255
  network 3.3.3.0 mask 255.255.255.252
  neighbor 1.2.3.4 activate
  neighbor 1.2.3.4 allowas-in 3
  neighbor 1.2.3.4 prefix-list PXL out
 exit-address-family
!

Note: I am able to extract the above code using awk or grep, but I want to translate my bash code to Python.

Thanks!

  • It may be useful for you to read this question and answer about using a customer field separator. [link](https://stackoverflow.com/questions/19600475/how-to-read-records-terminated-by-custom-separator-from-file-in-python) – T Burgis Sep 04 '18 at 12:42

2 Answers2

1

Try this:

from ciscoconfparse import CiscoConfParse

bgp = confparse.find_blocks(r"^router bgp 65500")
Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
Anna Patil
  • 31
  • 3
0

Thanks to another post on stackoverflow, I found a way to extract configuration sections from running config. Post is at Reading a file for a certain section in python.

Working code to extract "router bgp" section below:

bgp_found = False

bgp_section = []

with open('running-config', 'r') as f:
    for line in f.readlines():
        if 'router bgp' in line:
            bgp_found = True
            bgp_section.append(str(line).rstrip('\n'))  # this will append the section start to list
            continue
        if bgp_found:
            if line.startswith('!'):  # this will test if line starts with '!'
                bgp_found = False
            else:
                bgp_section.append(str(line).rstrip('\n'))
print (bgp_section)  # just for testing purposes; list would be used to extract rest of parameters

Hope it will be useful for others as well.