0

i have 2 line as a command output sh ip int bri and i want to fetch all up interfaces. my re expression matching one line which has FastEthernet0/0 but not loopback0. any suggestions please.

line

'Loopback0 1.1.1.1 YES NVRAM up up'

line1

'FastEthernet0/0 10.0.0.1 YES NVRAM up up'

match=re.search(r'\w+\d+?/?\d+?\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s+\w+\s+\w+\s+(up|down)\s+(up|down)', line1)

match.group()

'FastEthernet0/0 10.0.0.1 YES NVRAM up up'

match=re.search(r'\w+\d+?/?\d+?\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s+\w+\s+\w+\s+(up|down)\s+(up|down)', line)

match.group()

Traceback (most recent call last): File "", line 1, in match.group() AttributeError: 'NoneType' object has no attribute 'group'

2
  • 1
    You can update re to r'\w+[\d/]+\s+\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\s+\w+\s+\w+\s+(up|down)\s+(up|down) Commented Jan 2, 2017 at 8:10
  • @Kadir, it worked modified below:- r'\w+[\d+/]+\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+\w+\s+\w+\s+(up|down)\s+(up|down)', line) any comments about the error on below which did not work: r'\w+\d+/?\d+?\s+(\d{1,3}\.){3} \d{1,3}\s+\w+\s+\w+\s+(up|down)\s+(up|down)', /?\d+? and [\d/]+ makes the diff Commented Jan 2, 2017 at 8:36

1 Answer 1

1

a very verbose version of what you are looking for (with named groups (?P<name>regex) for easy access of the matches):

import re

re_str = '''
(?P<name>[\w/]+)                            # the name (alphanum + _ + /)
\s+                                         # one or more spaces
(?P<IP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})  # IP address
\s+                                         # one or more spaces
(?P<yesno>YES|NO)                           # yes (or no?)
\s+                                         # one or more spaces
(?P<type>\w+)                               # type (?)
\s+                                         # one or more spaces
(up|down)                                   # up (or down?)
\s+                                         # one or more spaces
(up|down)                                   # up (or down?)
'''

regex = re.compile(re_str, flags=re.VERBOSE)

text = '''Loopback0 1.1.1.1 YES NVRAM up up
FastEthernet0/0 10.0.0.1 YES NVRAM up up
FastEthernet0/0 10.0.0.1 YES NVRAM up up'''

for line in text.split('\n'):
    match = regex.match(line)
    print(match.group('name'), match.group('IP'))

this prints

Loopback0 1.1.1.1
FastEthernet0/0 10.0.0.1
FastEthernet0/0 10.0.0.1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.