有人知道如何通过windows命令行关闭单个连接的TCP或UDP套接字吗?

我在谷歌上搜索了一下,看到一些人也问了同样的问题。但是答案看起来像是netstat或netsh命令的手册页,重点关注如何监视端口。我不想要关于如何监控它们的答案(我已经这样做了)。我想干掉他们。

EDIT, for clarification: Let's say that my server listens TCP port 80. A client makes a connection and port 56789 is allocated for it. Then, I discover that this connection is undesired (e.g. this user is doing bad things, we asked them to stop but the connection didn't get dropped somewhere along the way). Normally, I would add a firewall to do the job, but this would take some time, and I was in an emergency situation. Killing the process that owns the connection is really a bad idea here because this would take down the server (all users would lose functionality when we just want to selectively and temporally drop this one connection).


当前回答

尝试Sysinternals/Microsoft的工具TCPView (GUI)和Tcpvcon(命令行)。 https://learn.microsoft.com/en-us/sysinternals/downloads/tcpview

其他回答

是的,这是可能的。你不必是当前拥有套接字的进程来关闭它。考虑一下,远程计算机、网卡、网线和操作系统都可能导致套接字关闭。

还要考虑Fiddler和Desktop VPN软件可以将自己插入到网络堆栈中,并显示您的所有流量或重新路由所有流量。

所以你真正需要的是Windows提供一个API,直接允许这样做,或者有人写了一个程序,操作起来有点像VPN或Fiddler,并给你一种方法来关闭通过它的套接字。

至少有一个程序(CurrPorts)可以做到这一点,我今天用它来关闭在CurrPorts启动之前启动的进程上的特定套接字。当然,要做到这一点,您必须以管理员身份运行它。

Note that it is probably not easily possible to cause a program to not listen on a port (well, it is possible but that capability is referred to as a firewall...), but I don't think that was being asked here. I believe the question is "how do I selectively close one active connection (socket) to the port my program is listening on?". The wording of the question is a bit off because a port number for the undesired inbound client connection is given and it was referred to as "port" but it's pretty clear that it was a reference to that one socket and not the listening port.

如果你在Windows 8、Windows Server 2012或更高版本上运行,并安装了PowerShell v4以上版本,你可以使用下面的脚本。它会发现与端口相关的进程并终止它们(即终止进程及其连接;不仅仅是联系)。

Code

#which port do you want to kill
[int]$portOfInterest = 80

#fetch the process ids related to this port
[int[]]$processId = Get-NetTCPConnection -LocalPort $portOfInterest | 
    Select-Object -ExpandProperty OwningProcess -Unique | 
    Where-Object {$_ -gt 0} 

#kill those processes
Stop-Process -Id $processId 

文档:

get - netttcpconnection - PowerShell的NetStat等效程序 选择对象-从对象中拉回特定属性/删除重复项 Where-Object -根据某些条件筛选值 Stop-Process - PowerShell的TaskKill等效程序

尝试Sysinternals/Microsoft的工具TCPView (GUI)和Tcpvcon(命令行)。 https://learn.microsoft.com/en-us/sysinternals/downloads/tcpview

Wkillcx是一个可靠的Windows命令行工具,用于从前面没有提到的命令行删除TCP连接。不过,它有时确实会在连接大量的服务器上出现问题。我有时使用tcpview进行交互式kill,但wkillcx可以在脚本中使用。

如果你知道你想要删除的特定端口,只需以admin的身份打开命令提示符(在windows上),然后:

NPX kill-port 1900

以上1900是我箱子的端口号。当我想关闭React-Native开发工具(和Expo)正在运行的端口时,我经常使用这个方法。原因是即使关闭了开发人员窗口或停止了服务器,端口仍然在使用中。