预防爆破MSSQL数据库PowerShell脚本求教
bat吧
全部回复
仅看楼主
level 1
技术媴 楼主
MSSQL数据库被爆破将IP加入黑名单的PowerShell脚本===不能正常使用:
# 使用 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
}
2025年01月18日 05点01分 1
level 1
技术媴 楼主
以上脚本中MSSQL使用的在执行后会提示无权限,有哪位能帮修正下吗?
2025年01月18日 05点01分 2
level 1
技术媴 楼主
以上三个脚本 还是会提示以下报错信息:
报错信息一: (这个报错信息不影响使用):
设置“OutputEncoding”时发生异常:“句柄无效。”
+ $OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]: ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
报错信息二:(使得脚本执行无法达到想要的效果):
Get-WinEvent : 尝试执行未经授权的操作。
+ $events = Get-WinEvent -FilterHashtable $filter -MaxEvents 100 -Oldes ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WinEvent], UnauthorizedAccessException
+ FullyQualifiedErrorId : 尝试执行未经授权的操作。,Microsoft.PowerShell.Commands.GetWinEventCommand
2025年01月18日 05点01分 3
1