Python正则表达式匹配多个并写入fi

2024-04-19 23:49:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,其中存储了来自多个Windows服务器的事件,这些事件是不分开的(所有导出都在一个长行中,有时是选项卡式的,有时不是)。你知道吗

我已经构建了regex来提取我想要存储在CSV中的信息(总共有20个匹配组),但是我现在正在尝试遍历文件中的许多行,并以CSV格式输出相关信息。我的代码如下:

#!/usr/bin/env python
import csv
import re

match1 = re.compile('(\D{3}  \d+ \d{2}[:]\d{2}[:]\d{2})')
<snipped for brevity>
match20 = re.compile('(?:Logon Type:  (.+?)   )')

regexes = [match1, match2, match3, match4, match5, match6, match7, match8, match9, match10, match11, match12, match13, match14, match15, match16, match17, match18, match19, match20]

pattern_combined = '|'.join(x.pattern for x in regexes)
print(pattern_combined)
print("End of combined regexes\n\n\n")

with open('Argus.csv', 'r') as fobj:
        with open('Argus1.csv', 'w') as resultFile:
                reader = csv.reader(fobj, delimiter=',')
                for row in reader:
                        output = re.findall(r'pattern_combined',row)
                        print(output)
                        print("End of OUTPUT\n\n\n")
                        out_str = ','.join(output)
                        print(out_str)
                        print("Final output\n\n\n")
                        resultFile.write(out_str)

为了我自己的理智,这里也进行了一些调试,试图查看它所采取的步骤,但我未能使其匹配(在print(output)时,我只得到一个空输出)

我已经在一行上用一个regex进行了测试,可以让它工作,但需要将它扩展到多个,每个匹配项都作为CSV中的一个字段导出,似乎无法进行。你知道吗

编辑:添加示例数据以显示所需提取的类型:

<13>Mar  8 05:56:00 PHCHBS-TP320161.XX.domain.net MSWinEventLog     4       Security        364388  Thu Mar 08 05:56:00 2018        4634    Microsoft-Windows-Security-Auditing     DOMAINNET\SYS_APM_XXXXXX1     N/A     Success Audit   PHCHBS-TP320161.XX.DOMAIN.net Logoff          An account was logged off.    Subject:   Security ID:  S-1-5-21-2025429265-1383384898-682003330-43805   Account Name:  SYS_APM_XXXXXX1   Account Domain:  DOMAINNET   Logon ID:  0xb1dfe060    Logon Type:   3    <truncated 199 bytes>       364387  

如您所见,相当标准的Windows事件格式,只是通过一些我无法控制的syslog进程推送到一个文件中,很遗憾!你知道吗


Tags: 文件csvreforoutputwindows事件out