pyparsing モジュールを使用した Snort ログの解析に問題があります。
問題は、Snort ログ (空白行で区切られた複数行のエントリがある) を分離し、行ごとに読み込んで文法が各行で機能することを期待するのではなく、pyparsing で各エントリをチャンク全体として解析することです (明らかに、そうではありません。)
各チャンクを一時的な文字列に変換して、各チャンク内の改行を削除しようとしましたが、正しく処理されません。私は完全に間違った方向に進んでいるかもしれませんが、そうは思いません (同様の形式は syslog タイプのログに対して完全に機能しますが、それらは 1 行のエントリであるため、基本的なファイル イテレータ/行処理に適しています)
これまでのログとコードのサンプルを次に示します。
[**] [1:486:4] ICMP Destination Unreachable Communication with Destination Host is Administratively Prohibited [**]
[Classification: Misc activity] [Priority: 3]
08/03-07:30:02.233350 172.143.241.86 -> 63.44.2.33
ICMP TTL:61 TOS:0xC0 ID:49461 IpLen:20 DgmLen:88
Type:3 Code:10 DESTINATION UNREACHABLE: ADMINISTRATIVELY PROHIBITED HOST FILTERED
** ORIGINAL DATAGRAM DUMP:
63.44.2.33:41235 -> 172.143.241.86:4949
TCP TTL:61 TOS:0x0 ID:36212 IpLen:20 DgmLen:60 DF
Seq: 0xF74E606
(32 more bytes of original packet)
** END OF DUMP
[**] ...more like this [**]
そして更新されたコード:
def snort_parse(logfile):
header = Suppress("[**] [") + Combine(integer + ":" + integer + ":" + integer) + Suppress("]") + Regex(".*") + Suppress("[**]")
cls = Optional(Suppress("[Classification:") + Regex(".*") + Suppress("]"))
pri = Suppress("[Priority:") + integer + Suppress("]")
date = integer + "/" + integer + "-" + integer + ":" + integer + "." + Suppress(integer)
src_ip = ip_addr + Suppress("->")
dest_ip = ip_addr
extra = Regex(".*")
bnf = header + cls + pri + date + src_ip + dest_ip + extra
def logreader(logfile):
chunk = []
with open(logfile) as snort_logfile:
for line in snort_logfile:
if line !='\n':
line = line[:-1]
chunk.append(line)
continue
else:
print chunk
yield " ".join(chunk)
chunk = []
string_to_parse = "".join(logreader(logfile).next())
fields = bnf.parseString(string_to_parse)
print fields
ヘルプ、ポインタ、RTFM、You're Doing It Wrongs など、大歓迎です。