我已经把这个powershell函数放在一起,基本上从脚本运行的最后一点($date变量)从NPS日志(特别拒绝身份验证尝试)中提取事件,整理出日志条目的IP和日期写入和将其添加到数组 ($array) 并将其导出到 CSV 日志。
然后我使用相同的数组 ($array) 对最近一小时的日志进行排序,查看是否存在 10 个或更多,并将符合该条件的任何日志移动到新数组 ($getip)。(有点像 fail2ban 设置,但适用于 Windows)
一切正常,除了在函数的末尾有一行我正在使用排序和计数记录,我算得很好,但它实际上不会删除 1 小时后的记录。
谁能看到我遗漏的任何东西?我很感激任何帮助。
function Get-DeniedIP {
$denied = 'C:\bin\denied.csv' #CSV log of IP's that have been linked to denied auth attempts
$whitelist = Import-Csv 'C:\bin\whitelist.csv' #Location of whitelist csv
$datepath = 'C:\bin\cache' #If it does not exist that is fine
$bannedip = 'C:\bin\banned.csv' #CSV log of IP's that have reached the max failed auth and are banned
$check = [System.IO.File]::Exists($datepath)
if ($check -like '*False*') {
(get-date).ToString() | Out-File $datepath
$date = Get-Date
}
else {
$date = Get-Content $datepath
$date = Get-Date -Date $date
}
$log = Get-EventLog -LogName Security -Message "*Network Policy Server denied*" -After $date
$array = @()
foreach ($message in $log) {
$address = ($message.message | Select-String -Pattern "Calling Station Identifier:\s*\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.Value
$address = ($address | Select-String -Pattern "\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.Value
$object = New-Object -TypeName PSObject
$object | Add-Member -Name 'IP' -MemberType Noteproperty -Value $address
$object | Add-Member -Name 'Date' -MemberType NoteProperty -Value $message.TimeWritten
$array += $object
}
$final = $array | where {$whitelist.IP -notcontains $_.IP}
if ($final -eq $null) {}
else {$final | Export-Csv $denied -Append}
$final
$DT = [DateTime]::Now.AddHours(-1)
$getip = $array | group-object -property IP | where {$_.Count -gt 10 -and
$array.Date -ge $DT} | Select -Property Name | Export-Csv $bannedip -Append
}
$DT = [DateTime]::Now.AddHours(-1)
包含完整的日期和时间,我建议删除除时间以外的所有内容,因为这可能会阻止脚本根据时间匹配日志。