【问题标题】:PowerShell Script to Disable/Re-enable a TCP/IP Port用于禁用/重新启用 TCP/IP 端口的 PowerShell 脚本
【发布时间】:2011-04-11 11:55:24
【问题描述】:

有没有办法在 PowerShell 中禁用和重新启用已知的 TCP/IP 端口?

【问题讨论】:

标签: powershell scripting tcp


【解决方案1】:

我会盲目假设您正在谈论禁用和启用由 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 个。要么您需要用户提供额外的参数,要么需要一些启发式方法来选择“正确”的站点。

【讨论】:

  • 我想这正是我需要的!非常感谢。
  • 再看一遍,我认为这不是我需要的。这是发生了什么:我们有一个名为 TM1 的 OLAP 工具,它在服务器上运行,并允许用户通过端口 12345 上的客户端工具进行连接。服务器上的多维数据集每天更新,但由于用户尝试连接和计算而减慢了速度.我想在更新发生时阻止他们连接,然后在更新完成后允许他们连接。服务必须运行才能进行更新。
  • 您必须 (a) 查阅 TM1 文档并希望他们有一种编程方式来切换连接而不关闭服务 (b) 在网络层阻止用户,即使用防火墙或 IPSEC 或类似的。
猜你喜欢
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多