powershell - 将防火墙日志转换为 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"
解决方案
有没有什么花哨的方法来代替遍历字符串
你这样做的任何方式都将涉及某种形式的读取和解析字符串。您可以通过使用正则表达式来匹配对来简化所需的代码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-Object
、Group-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 "
推荐阅读
- javascript - React - 使用 API 中的数据填充选择下拉列表
- javascript - 调用 clearInterval 后 setInterval 继续运行
- kubernetes - 在 kubernetes 中使用域部署入口 nginx
- python - 稀疏连接的网络 Keras
- c# - 使用 BlobContainerClient 将大型文件上传到 Azure
- dataweave - Mulesoft DataWeave:如何为带引号的字符串转义 $
- javascript - 有没有办法在 React JS 中查看已映射数组中的特定项目?
- node.js - 开始使用 Google Sheets API 无法获取配置/令牌文件
- vb6 - 获取点的颜色
- reactjs - 为什么背景颜色只应用于可见部分