从日志中获取重复的 IP 并写入新文档或日志



我正在尝试查找列出的 3 次以上的读取 IP 地址.log。 找到后,我想打印一次IP地址并将其写入writelist.log。

我一直在使用一组尝试这样做,但我不确定如何仅打印和写入 IP 地址。

例如,如果读取.log则包含...

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

我只想打印并将以下内容保存到写入列表中.log

255.255.255.255
10.5.5.5

使用我当前的代码,我正在打印并保存此代码...

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'])

我不想打印set([])或重复的 IP 地址。

我知道我可以使用string.replace()方法来摆脱其中的一些,但是有更好的方法来做到这一点吗?可能没有一套?

这是我的代码...

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()

使用Counter

import collections
with open('read.log', 'r+') as f:
# Place into a counter and remove trailing newline character
count = collections.counter(f.read().splitlines())

这将给

Counter({'10.1.89.11': 1, '255.255.255.255': 4, '10.5.5.5': 4})

然后,您可以循环访问Counter

for ip, n in count.items():
print(ip, n)
# Process the IP
...

这假定您收到的是干净的输入。在处理数据之前,您必须对其进行清理。

最新更新