我是 python 的初学者,我有一个包含 MBX_AUTHENTICATION_FAILED 的日志文件,我已经在其中获取了用户名、时间戳和 IP 地址的信息。
我的问题是如何从日志文件中获取更改密码 10 次的用户名,因为条件是每当用户更改密码 10 次时,我们需要用户的详细信息,例如用户名、时间戳和 IP地址。 这是我的日志文件:
20170119 193739188+0900 elim1td001p imapserv 52324 75559 132341478487808 Note;UserDataException(504/1) MBX_AUTHENTICATION_FAILED:{protocolType=[imap], userName=[teasst_emailrei_6000], password=[XXXXX]}:AuthenticateAndGetMailboxService\3aPOST:Authenticating Failed.::user=test_emaili_3000:cmd=1 LOGIN teasst_emailrei_6000 <password>:fromhost=129.0.0.1:sid=b34f10a-fd04-11e7-b246-7f629ba04def
这是我的python代码
import re
from csv import writer
import datetime
log_file = '/Users/kiya/Desktop/ip.txt'
output_file = '/Users/kiya/Desktop/output.csv'
name_to_check = 'MBX_AUTHENTICATION_FAILED'
with open(log_file,encoding="utf-8") as infile:
for line in infile:
if name_to_check in line:
username = re.search(r'(?<=userName=\[)(.*)(?=\],)', line)
username = username.group()
date = re.search(r'(?P<date>\d{8})\s+(?P<time>\d{9})\+(?P<zone>\d{4})', line)
date = datetime.datetime.strptime(date.group('date'), "%Y%m%d").strftime("%Y-%m-%d")
print(date)
time = re.search(r'(?P<date>\d{8})\s+(?P<time>\d{9})\+(?P<zone>\d{4})', line)
time = datetime.datetime.strptime(time.group('time'), "%H%M%S%f").strftime("%H:%M:%S")
print(time)
ip = re.search(r'(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])',line)
ip = ip.group()
with open(output_file, 'w') as outfile:
csv_writer = writer(outfile)
csv_writer.writerow(["Username","Date","Time","Ip"])
csv_writer.writerow([username,date,time,ip])
最佳答案
您可以将用户名附加到列表中,然后使用 collection.counter 获取计数:
from collections import Counter
usernamelist = []
usernamelist.append('tom')
usernamelist.append('tom')
usernamelist.append('tom')
usernamelist.append('sam')
usernamelist.append('louis')
c = Counter(usernamelist)
list_of_user_more_than_one = [i for i in c if c[i] > 1]
print(list_of_user_more_than_one)
--->['tom']
关于python - 如何使用python从日志文件中获取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50549742/