Regular expression for parsing network interface configuration
I am wondering if the problem can be solved with a single regex, or should I do a standard loop and evaluate line by line,
when i run the code i get the ['Ethernet0/22', 'Ethernet0/24']
result should be ['Ethernet0/23', 'Ethernet0/25']
.
any advice on this?
import re
txt='''#
interface Ethernet0/22
stp disable
broadcast-suppression 5
mac-address max-mac-count 1
port access vlan 452
#
interface Ethernet0/23
stp disable
description BTO
broadcast-suppression 5
port access vlan 2421
#
interface Ethernet0/24
stp disable
description Avaya G700
broadcast-suppression 5
port access vlan 452
#
interface Ethernet0/25
stp disable
description BTO
broadcast-suppression 5
port access vlan 2421
#
'''
re1 = '''^interface (.*?$).*?BTO.*?^#$'''
rg = re.compile(re1,re.IGNORECASE|re.DOTALL|re.MULTILINE)
m = rg.findall(txt)
if m:
print m
source to share
Here's a little parser for your file. Not only does it show a solution to your immediate problem, but the parser gives you a nice set of objects that you can use to easily access the data in each interface.
Here's the parser:
from pyparsing import *
# set up the parser
comment = "#" + Optional(restOfLine)
keyname = Word(alphas,alphanums+'-')
value = Combine(empty + SkipTo(LineEnd() | comment))
INTERFACE = Keyword("interface")
interfaceDef = Group(INTERFACE + value("name") + \
Dict(OneOrMore(Group(~INTERFACE + keyname + value))))
# ignore comments (could be anywhere)
interfaceDef.ignore(comment)
# parse the source text
ifcdata = OneOrMore(interfaceDef).parseString(txt)
Now how to use it:
# use dump() to list all of the named fields created at parse time
for ifc in ifcdata:
print ifc.dump()
# first the answer to the OP question
print [ifc.name for ifc in ifcdata if ifc.description == "BTO"]
# how to access fields that are not legal Python identifiers
print [(ifc.name,ifc['broadcast-suppression']) for ifc in ifcdata
if 'broadcast-suppression' in ifc]
# using names to index into a mapping with string interpolation
print ', '.join(["(%(name)s, '%(port)s')" % ifc for ifc in ifcdata ])
Prints out:
['interface', 'Ethernet0/22', ['stp', 'disable'], ['broadcast-suppression', '5'], ['mac-address', 'max-mac-count 1'], ['port', 'access vlan 452']]
- broadcast-suppression: 5
- mac-address: max-mac-count 1
- name: Ethernet0/22
- port: access vlan 452
- stp: disable
['interface', 'Ethernet0/23', ['stp', 'disable'], ['description', 'BTO'], ['broadcast-suppression', '5'], ['port', 'access vlan 2421']]
- broadcast-suppression: 5
- description: BTO
- name: Ethernet0/23
- port: access vlan 2421
- stp: disable
['interface', 'Ethernet0/24', ['stp', 'disable'], ['description', 'Avaya G700'], ['broadcast-suppression', '5'], ['port', 'access vlan 452']]
- broadcast-suppression: 5
- description: Avaya G700
- name: Ethernet0/24
- port: access vlan 452
- stp: disable
['interface', 'Ethernet0/25', ['stp', 'disable'], ['description', 'BTO'], ['broadcast-suppression', '5'], ['port', 'access vlan 2421']]
- broadcast-suppression: 5
- description: BTO
- name: Ethernet0/25
- port: access vlan 2421
- stp: disable
['Ethernet0/23', 'Ethernet0/25']
[('Ethernet0/22', '5'), ('Ethernet0/23', '5'), ('Ethernet0/24', '5'), ('Ethernet0/25', '5')]
(Ethernet0/22, 'access vlan 452'), (Ethernet0/23, 'access vlan 2421'), (Ethernet0/24, 'access vlan 452'), (Ethernet0/25, 'access vlan 2421')
source to share
Example without regex:
print [ stanza.split()[0]
for stanza in txt.split("interface ")
if stanza.lower().startswith( "ethernet" )
and stanza.lower().find("bto") > -1 ]
Explanation:
In my opinion, compositions are best read "inside out":
for stanza in txt.split("interface ")
Divide the text for each occurrence of the "interface" (including the next space). The resulting stanza will look like this:
Ethernet0/22
stp disable
broadcast-suppression 5
mac-address max-mac-count 1
port access vlan 452
#
Then filter the stanzas:
if stanza.lower().startswith( "ethernet" ) and stanza.lower().find("bto") > -1
This should be self-evident.
stanza.split()[0]
Divide the math stanzas in space and move the first item to the resulting list. This, in combination with the filter startswith
, will prevent IndexError
s
source to share
Instead of trying to create a pattern between the anchors ^ and $, and relying on #, you could use newlines to break sublines within a one-block match
eg. identify sentences in terms of a sequence of literal non-newlines leading to a newline.
something like
re1 = '''\ninterface ([^\n]+?)\n[^\n]+?\n[^\n]+BTO\n'''
will produce the result you run from the source provided.
source to share