python - 如何使用python从日志文件中获取特定数据

标签 python regex

我是 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/

相关文章:

python - 抓取包含::之前的网页

java - 需要转义 java 中 XML 标签(<、>、')之间存在的一些特殊字符

regex - Grep。不以 “abcd”结尾的文本行?

regex - 重写规则 : cannot compile regular expression - apache 2. 4.9

python - 使用 Django OAuth2 工具包生成单一访问 token

python - Web 从交互式网络 map 中抓取屏幕图像

regex - 我想优化使用 IN 子句和 regex_str 函数的存储过程。我不确定我应该如何优化它?

php - 仅匹配数字/波斯字符和拉丁字符

python - 是否可以在不连接网络的情况下通过 wifi 发送 UDP 广播?

python - 如何按两个元素对字典进行排序,只反转一个