Reputation: 119
I have a small Python script that calls a config file and a list. The list is used as the pattern to search the config file. The list is just IP addresses The script runs but it only finds the first IP on the list it doesn't step through each one to search the config.
Can someone tell me what I'm missing? I have tried to call a function but it still only finds the first IP on the list.
import re
list=['10.100.81.118',
'10.100.81.113',
'10.100.81.112',
'10.100.81.117',
'10.100.81.9',
'10.100.81.116',
'10.100.81.114',
'10.100.81.115',
'10.100.81.111',
'10.100.81.10',
'10.100.81.1']
config=open('show_run.txt','r')
for items in list:
for answers in config:
re2 = re.findall(items, answers, re.MULTILINE)
if re2:
print('\n'.join(re2))
Upvotes: 0
Views: 110
Reputation: 2451
As mentioned by @DaveStSomeWhere, the file needs to be reset to its initial position in each loop if not reading the file data.
So, you could do is read the file content to a variable and look in that to find a match.
import re
ip_list=['10.100.81.118', '10.100.81.113', '10.100.81.112',
'10.100.81.117', '10.100.81.9', '10.100.81.116',
'10.100.81.114', '10.100.81.115', '10.100.81.111',
'10.100.81.10', '10.100.81.1']
config= open('show_run.txt', 'r')
configdata = config.read()
for items in ip_list:
re2 = re.findall(items, configdata, re.MULTILINE)
if re2:
print('\n'.join(re2))
OR simply you could do this without the re module:
for items in ip_list:
if items in configdata:
print('\n'.join(items))
Upvotes: 1
Reputation: 530
Regex can actually help you search for all of the items in your list at the same time:
import re
my_list = ['10.100.81.118', '10.100.81.113', '10.100.81.112',
'10.100.81.117', '10.100.81.9', '10.100.81.116',
'10.100.81.114', '10.100.81.115', '10.100.81.111',
'10.100.81.10', '10.100.81.1']
pattern = r'({})'.format('|'.join(my_list))
print (pattern)
example1 = 'this is an ip address: 10.100.81.9 10.100.81.9 and this is another: 10.100.81.113'
example2 = 'this is an ip address: 10.100.81.10 and this is another: 10.100.81.113'
config = [example1, example2]
for answers in config:
res = re.findall(pattern, answers)
print (res)
Upvotes: 1