有人知道如何通过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).


当前回答

如果你在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等效程序

其他回答

例如,您希望释放端口8080 然后,按照这些命令执行。

 netstat -ano
 taskkill /f /im [PID of the port 8080 got from previous command]

完成了!

CurrPorts不适合我们,我们只能通过ssh访问服务器,所以也没有TCPView。为了不断开其他连接,我们也不能终止该进程。我们最终做的是在Windows的防火墙上阻止连接,但这还没有被建议。是的,这将阻止所有符合规则的连接,但在我们的情况下,只有一个连接(我们感兴趣的):

netsh advfirewall firewall add rule name="Conn hotfix" dir=out action=block protocol=T
CP remoteip=192.168.38.13

替换为您需要的IP,并根据需要添加其他规则。

如果没有拥有这些套接字,就不能关闭服务器上的套接字,因此如果没有在拥有服务器套接字的进程中运行代码,就不能实际关闭套接字。

然而,还有另一个选项告诉客户端关闭它的套接字。向客户端正在连接的端口发送RST TCP包将导致客户端断开连接。你可以使用nmap进行RST扫描。

http://nmap.org/

为了关闭该端口,您可以确定正在侦听该端口的进程并杀死该进程。

使用CurrPorts(免费且无需安装):http://www.nirsoft.net/utils/cports.html

/close <本端地址> <本端端口> <对端地址> <对端端口>{进程名}

例子:

# Close all connections with remote port 80 and remote address 192.168.1.10: 
/close * * 192.168.1.10 80
# Close all connections with remote port 80 (for all remote addresses): 
/close * * * 80
# Close all connections to remote address 192.168.20.30: 
/close * * 192.168.20.30 *
# Close all connections with local port 80: 
/close * 80 * *
# Close all connections of Firefox with remote port 80: 
/close * * * 80 firefox.exe

它还有一个很好的GUI,具有搜索和筛选功能。

注意:这个答案是huntharo和JasonXA的答案和评论组合在一起,并进行了简化,以方便读者阅读。例子来自CurrPorts的网页。