yuchenr
357 天前
$startTime = Get-Date
$startTimeStr = $startTime.AddMinutes(-5).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFZ")
$failedAttemptsThreshold = 3
$Query = [xml]@"
<QueryList>
<Query Id="0" Path="Security">
<Select Path="Security">*[System[(EventID=4625) and TimeCreated[@SystemTime>='$startTimeStr']]]</Select>
</Query>
</QueryList>
"@
function Get-IPAddresses {
param (
[xml]$query,
[int]$maxEvents
)
$events = Get-WinEvent -FilterXml $query -MaxEvents $maxEvents
if (-not $events) {
Write-Host "未获取到任何日志。脚本将退出。"
return
}
$events | ForEach-Object {
$_.Properties[19].Value
}
}
$failedIPs = Get-IPAddresses -query $Query -maxEvents 100 | Group-Object | Where-Object {
$_.Count -gt $failedAttemptsThreshold
} | Select-Object -ExpandProperty Name -Unique
$uniqueIPs = Get-IPAddresses -query $Query -maxEvents 100 | Select-Object -Unique
$filteredFailedIPs = $failedIPs | Where-Object {
$_ -notmatch '^192\.168\.' -and $_ -notmatch '^10\.' -and $_ -notmatch '^172\.(1[6-9]|2[0-9]|3[0-1])\.'
}
# 定义要过滤的特定 IP 地址列表
$specificIPs = @("192.168.1.100", "10.0.0.5")
# 过滤掉特定 IP 地址
$filteredFailedIPs = $filteredFailedIPs | Where-Object {
$_ -notin $specificIPs
}
$ruleName = "BlockIPs"
$filteredFailedIPs = $filteredFailedIPs | Sort-Object
# 获取现有的防火墙规则
$existingRule = Get-NetFirewallRule -DisplayName $ruleName
if ($existingRule) {
# 获取现有的远程地址过滤器
$existingAddressFilters = Get-NetFirewallAddressFilter -AssociatedNetFirewallRule $existingRule
# 获取现有的远程地址
$existingRemoteAddresses = $existingAddressFilters | Select-Object -ExpandProperty RemoteAddress
$existingRemoteAddresses = @($existingRemoteAddresses)
$existingAddressFilters = @($existingAddressFilters)
# 添加新的地址
$newRemoteAddresses = $existingRemoteAddresses + $filteredFailedIPs | Select-Object -Unique
# 更新远程地址过滤器
$existingAddressFilters | Set-NetFirewallAddressFilter -RemoteAddress $newRemoteAddresses
}
else {
Write-Host "规则 $ruleName 不存在。"
New-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Action Block -Protocol Any -RemoteAddress $filteredFailedIPs -RemoteAddressType "IP"
}