添加防火墙脚本的例外

时间:2013-11-11 01:46:32

标签: powershell powershell-v2.0 powershell-v3.0

所以我不会赞成这个剧本,但我需要一些帮助。 我是PS的新手,所以请原谅这些愚蠢的问题。

我需要为此脚本添加例外,例如“192.168”。 /“10.0。”范围。

我知道它会是这样的:  如果remoteaddress =“blah”则跳过。

但我不知道如何为powershell格式化它。

如果有人可以告诉我或指出我正确的方向?

#Checks for IP addresses that used incorrect password more than 10 times
#within 24 hours and blocks them using a firewall rule 'BlockAttackers'

#Check only last 24 hours
$DT = [DateTime]::Now.AddHours(-24)

#Select Ip addresses that has audit failure
$l = Get-EventLog -LogName 'Security' -InstanceId 4625 -After $DT | Select-Object @{n='IpAddress';e={$_.ReplacementStrings[-2]} }

#Get ip adresses, that have more than 10 wrong logins
$g = $l | group-object -property IpAddress | where {$_.Count -gt 10} | Select -property Name

#Get firewall object
$fw = New-Object -ComObject hnetcfg.fwpolicy2

#Get firewall rule named 'BlockAttackers'
$ar = $fw.rules | where {$_.name -eq 'BlockAttackers'}

#Split the existing IPs into an array so we can search it for existing IPs
$arRemote = $ar.RemoteAddresses -split(',')

#Only collect IPs that aren't already in the firewall rule
$w = $g | where {$_.Name.Length -gt 1 -and !($arRemote -contains $_.Name + '/255.255.255.255') }

#Add the new IPs to firewall rule
$w| %{
  if ($ar.RemoteAddresses -eq '*') {
    $ar.remoteaddresses = $_.Name
  }else{
    $ar.remoteaddresses += ',' + $_.Name
  }
}

#Write to logfile
if ($w.length -gt 1) {
  $w| %{(Get-Date).ToString() + ' ' + $_.Name >> '.\blocked.txt'}
}

1 个答案:

答案 0 :(得分:1)

你想要的是一个你永远不想阻止的白名单。

如果遇到列入白名单的IP,那么这是一个失败的情况。

$whitelist = @("10.0.0.1", "192.168.1.1")
..
if ($IP -match $whitelist)  { 
    #do nothing, debug here 
} else { 
    #block things 
}

对于你的PowerShell体验级别来说,这可能有点棘手,但请看一下wail2ban,这是我创建的一个PowerShell脚本,可以解决这个问题。