【问题标题】:Python log.txt making fancy. grep/regexPython log.txt 变得花哨。 grep/正则表达式
【发布时间】:2017-01-12 08:52:43
【问题描述】:

有一个log.txt。

“[25-Feb-2016 11:27:16 +0200]: 登录失败 .... 212.153.100.19 获取/....emailaddress@email.com”........

我如何编写一个脚本,它可以只对我的日期/IP 地址和电子邮件地址进行 grep 或正则表达式,并将其写入另一个 .txt。

最重要的是我需要日期和相应的 IP 和电子邮件。

我尝试使用下一个代码,但它是对所有数据的分段..

import os
import re
import datetime


filename = 'log.txt'
newfilename = 'output.txt'


if os.path.exists(filename):
    data = open(filename,'r')
    bulkemails = data.read()


else:
    print "File not found."
    raise SystemExit


r = re.compile(r'[\w\.-]+@[\w\.-]+\b')
results = r.findall(bulkemails)    

emails = ""   
for x in results:
    emails += str(x)+"\n"   



ip = re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
result = ip.findall(bulkemails)

ip =""
for y in result:
    ip += str(y)+"\n"


dt = re.compile(r'(\d{4})-(\d{2})-(\d{2})')
result = dt.findall(bulkemails)

dt =""
for z in result:
    dt += str(z)+"\n"




def writefile():
    f = open(newfilename, 'w')
    f.write(emails + ip + dt)
    f.close()
    print "File written."


def overwrite_ok():
    response = raw_input("Are you sure you want to overwrite "+str(newfilename)+"? Yes or No\n")
    if response == "Yes":
        writefile()
    elif response == "No":
        print "Aborted."
    else:
        print "Please enter Yes or No."
        overwrite_ok()


if os.path.exists(newfilename):
    overwrite_ok()      
else: 
    writefile()

所以我希望与 output.txt 相同的内容包含在下一个:

2016 年 2 月 25 日 11:27:16 +0200] -- 212.153.100.19 -- emailaddress@email.com"

2016 年 2 月 25 日 11:27:16 +0200] -- 212.153.100.10 -- emailaddress1@email.com"

2016 年 2 月 25 日 11:27:16 +0200] -- 212.153.100.11 -- emailaddress2@email.com"

感谢您的帮助,祝您有美好的一天:)

【问题讨论】:

    标签: python regex email grep


    【解决方案1】:

    您应该创建一个包含三组的正则表达式,一组用于时间,一组用于 IP,一组用于电子邮件。

    import re
    my_regex = re.compile(r".+?(\d{2}-\w+-\d{4}).+?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).+?\b([\w.\d]+@[\w.\d]+)(?:\b|$)")
    with open("somefile") as f_logs:
        logs = f_logs.readlines()
    for line in logs:
        my_regex.sub(r"[\1] -- \2 -- \3",line)
    

    您可以在regex101查看它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 2023-03-04
      • 1970-01-01
      • 2014-06-29
      • 2018-04-16
      相关资源
      最近更新 更多