|
本帖最后由 1G空间100元 于 2025-1-18 17:15 编辑
服务器上安装了MSSQL数据库
查看事件日志 发现有外网IP不停的爆破远MSSQL数据库 产生大量的记录日志
用PowerShell脚本来提取事件日志中的IP 然后创建防火墙规则进行屏蔽
将以下脚本保存为PS1后 创建计划任务运行
MSSQL数据库被爆破将IP加入黑名单的PowerShell脚本
需要用system用户运行脚本;可以创建计划任务用system执行计划任务:
# 使用 Get-WinEvent 检索事件日志,找到日志ID,提取其中的远程IP地址,将这个地址写入到防火墙阻止规则内
# 设置控制台输出编码为 GB2312 或 GBK
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding("GB2312")
# 定义日志名称和事件ID
$logName = "Application" # 安全日志=Security 应用程序日志=Application 对应<Channel>的值
$eventID = 18456 # 事件ID 对应<EventID>的值
# 定义时间范围
$startTime = (Get-Date).AddDays(-1) # 从一天前开始
$endTime = Get-Date # 到现在
# 检索指定时间范围内的事件日志条目
$filter = @{
LogName = $logName
ID = $eventID
StartTime = $startTime
EndTime = $endTime
}
# 使用MaxEvents来设置最大日志读取条数,Oldest按事件写入的顺序输出事件,从最早到最新
$events = Get-WinEvent -FilterHashtable $filter -MaxEvents 100 -Oldest
foreach ($event in $events) {
$message = $event.Message
# 显示完全日志内容,用于调试
# Write-Output "完全日志内容:"
# Write-Output $message
# Write-Output "----------------------------------------"
# 使用正则匹配IP地址,这里由于Windows语言版本的不同,这样匹配成功率更高
if ($message -match "(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::(\d{1,5}))?") {
$sourceAddress = $matches[1] # 匹配到IP地址
if ($sourceAddress -eq "127.0.0.1" -or $sourceAddress -eq "0.0.0.0") {
# 如果是本地回环地址,则跳过后续操作
# 如果是安全的,你已知的IP也可以加到这个步骤内
Write-Output "IP Address is localhost (127.0.0.1). 跳过防火墙规则创建."
Write-Output "----------------------------------------"
continue
}
# 检查防火墙规则是否已存在
$existingRule = Get-NetFirewallRule -DisplayName "Block IP $sourceAddress" -ErrorAction SilentlyContinue
if ($existingRule) {
Write-Output "IP $sourceAddress 防火墙规则已存在,跳过创建."
} else {
# 创建防火墙规则禁止连接该IP地址
New-NetFirewallRule -DisplayName "Block IP $sourceAddress" -Direction Inbound -Action Block -RemoteAddress $sourceAddress
Write-Output "IP $sourceAddress 防火墙规则已新建"
}
} else {
$sourceAddress = "N/A"
}
Write-Output $sourceAddress
}
|
|