【发布时间】:2011-04-11 11:55:24
【问题描述】:
有没有办法在 PowerShell 中禁用和重新启用已知的 TCP/IP 端口?
【问题讨论】:
-
你是指网络适配器还是 TCP 端口?
-
我建议使用防火墙。 github.com/PowerShell/xNetworking#adding-a-firewall-rule 是一种方式。
标签: powershell scripting tcp
有没有办法在 PowerShell 中禁用和重新启用已知的 TCP/IP 端口?
【问题讨论】:
标签: powershell scripting tcp
我会盲目假设您正在谈论禁用和启用由 IIS 托管的 TCP/IP 套接字。 (不是,比如说,寻找在防火墙级别阻止/解除阻止的方法,或者完全是其他的东西。)在这种情况下,我碰巧有必要的脚本在周围......
# Get the IIsWebServer and IIsWebServerSetting WMI objects matching a display name, and combine them into one object
function Get-IIsWeb
{
param (
[string] $displayName = "",
[string] $computer = "localhost"
)
if ($displayName -eq "")
{ $filter = "" }
else
{ $filter = "ServerComment='$displayName'"}
Get-WmiObject -namespace "root\MicrosoftIISv2" -class "IIsWebServerSetting" -filter $filter -computer $computer -authentication 6 | % {
$temp = $_
Get-WmiObject -namespace "root\MicrosoftIISv2" -class "IIsWebServer" -filter "Name='$($_.Name)'" -computer $computer -authentication 6 |
add-member -membertype NoteProperty -name Settings -value $temp -passthru
}
}
# Stop all websites on a given computer that are bound to the specified port, unless they are scoped to a
# host header or IP address
function Stop-WebsiteOnPort
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, valuefrompipeline=$true)]
[int] $port,
[Parameter(Position=0)]
[string] $computer = "localhost",
[Parameter()]
[string] $hostName = $null,
[Parameter()]
[string] $ip = $null
)
begin { $websites = Get-IIsWeb -computer $computer }
process
{
# I don't think you can do this filter in WQL
$websites |
? {
( $_.settings.serverbindings | ? {$_.port -eq $port -and $_.Hostname -eq $hostName -and $_.IP -eq $ip} | measure).count -gt 0
} |
% {
$_.stop()
}
}
}
重新启用站点的实际 WMI 代码与上面看到的停止站点的代码几乎相同。但是,您需要做更多的工作:可能有任意多个站点配置为使用给定端口,但一次只能运行 1 个。要么您需要用户提供额外的参数,要么需要一些启发式方法来选择“正确”的站点。
【讨论】: