首页 > 解决方案 > 将防火墙日志转换为 Powershell 哈希表

问题描述

我有一个 Sophos UTM 的防火墙日志,其中包含几个条目,这些条目看起来像最后的示例(每个条目都是一行)。

我想编写一个 Powershell 脚本来统计特定规则匹配的频率以及类似的内容。为了执行这些分析,我想将日志的每一行转换为哈希表,以便我可以轻松访问条目的信息。

有没有什么花哨的方法来代替迭代一个字符串,它包含防火墙日志的一行和匹配的字符(例如搜索“=”,然后搜索该位置的左侧和右侧以获取属性和相应的值)找到成对的属性值?

任何如何将数据转换为可用格式的帮助和想法将不胜感激!

2021:09:08-00:02:45 fwtest ulogd[4040]: id="2021" severity="info" sys="SecureNet" sub="packetfilter" name="Packet dropped" action="drop" fwrule="60019" initf="eth2" srcmac="01:23:45:67:89:ab" dstmac="ba:98:76:54:32:10" srcip="10.0.0.1" dstip="10.0.1.1" proto="17" length="96" tos="0x00" prec="0x00" ttl="45" srcport="1234" dstport="4321"

标签: powershellhashtable

解决方案


有没有什么花哨的方法来代替遍历字符串

你这样做的任何方式都将涉及某种形式的读取和解析字符串。您可以通过使用正则表达式来匹配对来简化所需的代码name="value"

# Replace this string array with `Get-Content path\to\log\file(s).log` 
@(
  '2021:09:08-00:02:45 fwtest ulogd[4040]: id="2021" severity="info" sys="SecureNet" sub="packetfilter" name="Packet dropped" action="drop" fwrule="60019" initf="eth2" srcmac="01:23:45:67:89:ab" dstmac="ba:98:76:54:32:10" srcip="10.0.0.1" dstip="10.0.1.1" proto="17" length="96" tos="0x00" prec="0x00" ttl="45" srcport="1234" dstport="4321"'
) |Select-String -Pattern '\b(\w+)\="([^"]+)"' -AllMatches |ForEach-Object {
  # Create an ordered dictionary to hold the name-value pairs
  $props = [ordered]@{}

  # Iterate over each pair found by Select-String
  $_.Matches |ForEach-Object {
    # Add each name-value pair to the dictionary
    $props[$_.Groups[1].Value] = $_.Groups[2].Value
  }

  # Convert dictionary to PSObject
  [pscustomobject]$props
}

这将在每个日志行生成 1 个新对象,您可以使用内置实用程序(如Where-ObjectGroup-Object等)来处理这些对象Measure-Object

使用的正则表达式模式 ( \b(\w+)\="([^"]+)") 描述:

\b          # match a word boundary
  (         # capture group start
   \w+      # match 1 or more word characters (letters or numbers)
  )         # capture group end
  \="       # match a literal = followed by "
  (         # capture group start
   [^"]+    # match 1 or more of any characters except "
  )         # capture group end
  "         # match a literal "

推荐阅读