I am trying to find IP addresses in read.log that are listed more than 3 times. Once found, I want to print the IP address once and write it to writelist.log.
I have been trying this using a set but I am not sure how I can print and write only the IP address.
For example, if read.log contains...
10.1.89.11
255.255.255.255
255.255.255.255
10.5.5.5
10.5.5.5
10.5.5.5
10.5.5.5
255.255.255.255
255.255.255.255
I just want to print and save the below to writelist.log
255.255.255.255
10.5.5.5
With my current code, I am printing and saving this...
set([])
set([])
set([])
set([])
set([])
set([])
set(['10.5.5.5'])
set(['10.5.5.5'])
set(['10.5.5.5', '255.255.255.255'])
I do not want to print set([])
or duplicate IP addresses.
I know I could use the string.replace()
method to get rid of some of that but is there a better way to do this? Possibly without a set?
Here is my code...
import re
login_attempts = 3
def run():
try:
with open("read.log", "r+") as log:
ip_list = []
for line in log:
address = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
match = re.match(address, line)
if (match):
match = match.group()
ip_list.append(match.strip())
s = set([i for i in ip_list if ip_list.count(i) > login_attempts])
strs = repr(s) # use repr to convert to string
with open("writelist.log", "a") as f:
f.write(strs)
else:
continue
log.close
except OSError as e:
print (e)
run()