gpt4 book ai didi

python - 从日志中获取循环 IP 并写入新文档或日志

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:06 31 4
gpt4 key购买 nike

我试图在 read.log 中查找列出次数超过 3 次的 IP 地址。一旦找到,我想打印一次IP地址并将其写入writelist.log。

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

例如,如果 read.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

我只是想打印以下内容并将其保存到 writelist.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
...

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

关于python - 从日志中获取循环 IP 并写入新文档或日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50919137/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com