在 Server 2008 R2 计算机上,我想使用 Powershell 查询特定规则的“远程地址”列表。相关规则是通过应用于计算机的组策略创建的。
我知道有netsh advfirewall firewall show rule name=<name>
以及返回的列表(New-object –comObject HNetCfg.FwPolicy2).rules
,但两者似乎仅包含本地定义的规则,并且没有列出防火墙 GPO 扩展创建的任何规则。
如何方便地获取策略创建的规则的属性?
答案1
我求助于解析组策略防火墙扩展写入的字符串HKLM\SOFTWARE\Policies\Microsoft\WindowsFirewall\FirewallRules
。以下是特定规则的原始注册表值数据:
v2.10|Action=Allow|Active=TRUE|Dir=In|Protocol=6|LPort=5666|RA4=192.168.21.55|RA4=192.168240.10|RA4=192.168.240.11|RA4=192.168.240.12|App=%ProgramFiles%\NSClient++\nscp.exe|Name=NSClient++ Monitoring Agent|Desc=Allow NSClient/NRPE connections from Nagios servers|
因为这些是Name=Value
数据对,“姓名”并不是唯一的,除了一系列Split()
调用之外,还有一些工作要做,但它仍然足够干净,可以在 PowerShell v2 及更高版本中使用:
Function Get-GPOFirewallRules()
{
$regPath="HKLM:\SOFTWARE\Policies\Microsoft\WindowsFirewall\FirewallRules"
# fetch rule value strings from registry into an array of strings,
# map version info and GPO rule ID into fields in string
$rulesRaw = (Get-ItemProperty -Path $regPath).PSObject.Properties | `
Where-Object { $_.Name -like "{[0-9A-F\-]*}" } | `
Select-Object "Name", "Value" | `
ForEach-Object { $_.Value -replace "^(v[0-9\.]*)\|", `
"GPOID=$($_.Name)|GPOVERSION=`$1|" }
# construct a result set of hashtables
$rulesRaw | ForEach-Object {
$rule=@{} # initialize as hashtable
$_.Split("|") | ForEach-Object {
$name = $_.Split("=")[0]
$value = $_.Split("=")[1]
# for multi-valued names, cast to array and add value element
If ($rule.ContainsKey($name)) {
$rule.$name = [array]($rule.$name) + $value
} Else {
$rule.Add($name, $value)
}
} # $_.Split("|") | ForEach-Object
$rule
} #$rulesRaw | ForEach-Object
}
输出是一个哈希表列表,其中键名称来自相应的注册表字段名称,而值是字符串或字符串数组:
Get-GPOFirewallRules
Action Allow
GPOVERSION v2.10
Dir In
Desc Allow NSClient/NRPE connections from Nagios servers
Name NSClient++ Monitoring Agent
Active TRUE
RA4 {192.168.21.55, 192.168.240.10, 192.168.240.11, 192.168.240.12}
App %ProgramFiles%\NSClient++\nscp.exe
Protocol 6
LPort 5666
GPOID {1FEFA84F-0779-4279-9C02-F5678C949304}
Action Allow
GPOVERSION v2.10
Dir In
Name Allow ICMP for Monitoring und Management
Active TRUE
RA4 {192.168.21.55, 192.168.3.60, 192.168.3.61, 192.168.8.0/255.255.255.0...}
ICMP4 {3:*, 8:*, 11:*}
Protocol 1
GPOID {6CA2C52C-6AD6-4513-B197-3702637BD9DF}
命名方案与(New-object –comObject HNetCfg.FwPolicy2).rules
返回的方案不同,结构似乎也略有不同(并且在未来 Windows 版本中可能会发生变化),但目前看来它已经达到了其目的。