使用 PowerShell 终止 TCP 连接

问题描述 投票:0回答:1

我需要一个命令来终止单个打开的 TCP 连接。我浏览了几个论坛,但如果不下载第 3 方工具,我无法获得明确的答案。

Proto  Local Address          Foreign Address        State
TCP    10.0.0.0:59614          SSHServer1:ssh      ESTABLISHED
TCP    10.0.0.0:59648          SSHServer2:ssh      ESTABLISHED

目标是从中枚举单个值:

$ConnectionToKill = netstat | Select-String -SimpleMatch 'ServerSSH1' | ConvertFrom-String | Select-Object p4

并使用变量 $ConnectionToKill 关闭连接

windows powershell tcp server
1个回答
0
投票

虽然这个问题是前一段时间提出的,但我想提供一个更全面的解决方案,可能对面临类似问题的其他人有所帮助。

要在不使用第三方工具的情况下终止 PowerShell 中的特定 TCP 连接,我们可以使用 Windows API 中的

SetTcpEntry
函数。这是一个完整的解决方案,其中包括关闭 TCP 连接的功能:

# Define Win32 API functions
Add-Type -TypeDefinition @"
    using System;
    using System.Runtime.InteropServices;

    public class TcpHelper
    {
        [DllImport("iphlpapi.dll", SetLastError=true)]
        public static extern int SetTcpEntry(IntPtr pTcpRow);

        [StructLayout(LayoutKind.Sequential)]
        public struct MIB_TCPROW
        {
            public uint dwState;
            public uint dwLocalAddr;
            public uint dwLocalPort;
            public uint dwRemoteAddr;
            public uint dwRemotePort;
        }
    }
"@

<#
.SYNOPSIS
Closes a specified TCP connection.

.DESCRIPTION
The Close-TcpConnection function closes a TCP connection using the Windows API. It takes a connection object (typically obtained from Get-NetTCPConnection) as input and forcibly closes the connection.

.PARAMETER Connection
An object representing the TCP connection to be closed. This should be an object returned by the Get-NetTCPConnection cmdlet.

.EXAMPLE
$connection = Get-NetTCPConnection -LocalPort 12345 | Select-Object -First 1
Close-TcpConnection -Connection $connection

This example closes the TCP connection on local port 12345.

.NOTES
This function requires administrative privileges to run successfully.
#>
function Close-TcpConnection {
    param (
        [Parameter(Mandatory=$true)]
        [object]$Connection
    )

    if ($null -eq $Connection) {
        Write-Host "Connection is null"
        return
    }

    # Create MIB_TCPROW structure
    $tcpRow = New-Object TcpHelper+MIB_TCPROW
    $tcpRow.dwState = 12  # MIB_TCP_STATE_DELETE_TCB
    $tcpRow.dwLocalAddr = [System.BitConverter]::ToUInt32([System.Net.IPAddress]::Parse($Connection.LocalAddress).GetAddressBytes(), 0)
    $tcpRow.dwLocalPort = [uint16]$Connection.LocalPort -shl 8 -bor [uint16]$Connection.LocalPort -shr 8
    $tcpRow.dwRemoteAddr = [System.BitConverter]::ToUInt32([System.Net.IPAddress]::Parse($Connection.RemoteAddress).GetAddressBytes(), 0)
    $tcpRow.dwRemotePort = [uint16]$Connection.RemotePort -shl 8 -bor [uint16]$Connection.RemotePort -shr 8

    # Allocate unmanaged memory and copy structure
    $pTcpRow = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([System.Runtime.InteropServices.Marshal]::SizeOf($tcpRow))
    [System.Runtime.InteropServices.Marshal]::StructureToPtr($tcpRow, $pTcpRow, $false)

    # Call SetTcpEntry
    $result = [TcpHelper]::SetTcpEntry($pTcpRow)

    # Free unmanaged memory
    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($pTcpRow)

    if ($result -eq 0) {
        Write-Host "Successfully closed TCP connection"
    } else {
        Write-Host "Failed to close TCP connection, error code: $result"
    }
}

使用方法如下:

  1. 首先,找到您要关闭的连接:
$ConnectionToKill = Get-NetTCPConnection | Where-Object { $_.RemoteAddress -eq 'SSHServer1' -and $_.RemotePort -eq 22 } | Select-Object -First 1
  1. 然后,使用
    Close-TcpConnection
    函数关闭连接:
Close-TcpConnection -Connection $ConnectionToKill

注意:此脚本可能需要管理权限才能运行。

© www.soinside.com 2019 - 2024. All rights reserved.