Powershell开放端口配置文件,全部(私有公共域)

时间:2012-10-01 12:35:05

标签: powershell

我有一个PowerShell脚本打开端口5555,但它默认为profile = private,当我希望它是全部(私有,公共,域)时。如何修改脚本来实现此目的?

$port = New-Object -ComObject HNetCfg.FWOpenPort
$port.Port = 5555
$port.Name = 'MyPort'
$port.Enabled = $true

$fwMgr = New-Object -ComObject HNetCfg.FwMgr
$profile = $fwMgr.LocalPolicy.CurrentProfile
$profile.GloballyOpenPorts.Add($port)

$port = New-Object -ComObject HNetCfg.FWOpenPort
$port.Port = 6521
$port.Name = 'ArkleSQL'
$port.Enabled = $true

$fwMgr = New-Object -ComObject HNetCfg.FwMgr
$profile = $fwMgr.LocalPolicy.CurrentProfile
$profile.GloballyOpenPorts.Add($port)

2 个答案:

答案 0 :(得分:2)

COM对象有两个值用于防火墙管理。 0表示域网络,1表示标准网络。似乎(在此API中)不区分此公共和私人配置文件。

您可以替换

的最后一部分
$fwMgr = New-Object -ComObject HNetCfg.FwMgr
$profile = $fwMgr.LocalPolicy.CurrentProfile
$profile.GloballyOpenPorts.Add($port)

$Profiles = @{
    NET_FW_PROFILE_DOMAIN = 0
    NET_FW_PROFILE_STANDARD = 1
}

$fwMgr = New-Object -ComObject HNetCfg.FwMgr

$profile.GloballyOpenPorts.Add($port)
foreach ($ProfileKey in $Profiles.Keys)
{
    $Profile = $fwMgr.LocalPolicy.GetProfileByType($profiles[$ProfileKey])
    $Profile.GloballyOpenPorts.Add($Port)
}

答案 1 :(得分:1)

您可以使用FwPolicy2FWRule为所有配置文件创建规则:

$fwPolicy = New-Object -ComObject HNetCfg.FwPolicy2

$rule = New-Object -ComObject HNetCfg.FWRule
$rule.Name = 'MyPort'
$rule.Profiles = $NET_FW_PROFILE2_ALL
$rule.Enabled = $true
$rule.Action = $NET_FW_ACTION_ALLOW
$rule.Direction = $NET_FW_RULE_DIR_IN
$rule.Protocol = $NET_FW_IP_PROTOCOL_TCP
$rule.LocalPorts = 5555

$fwPolicy.Rules.Add($rule)

以下是使用的常量:

$NET_FW_PROFILE2_DOMAIN = 1
$NET_FW_PROFILE2_PRIVATE = 2
$NET_FW_PROFILE2_PUBLIC = 4
$NET_FW_PROFILE2_ALL = 2147483647

$NET_FW_IP_PROTOCOL_TCP = 6
$NET_FW_IP_PROTOCOL_UDP = 17
$NET_FW_IP_PROTOCOL_ICMPv4 = 1
$NET_FW_IP_PROTOCOL_ICMPv6 = 58

$NET_FW_RULE_DIR_IN = 1
$NET_FW_RULE_DIR_OUT = 2

$NET_FW_ACTION_BLOCK = 0
$NET_FW_ACTION_ALLOW = 1

(资料来源:http://www.ohmancorp.com/files/RefWin-AdvFirewall-JCopyFWRules.txt