有人知道如何通过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等效程序
如果不关闭拥有这些套接字的进程,就不能关闭套接字。套接字属于打开它们的进程。因此要找出Unix/Linux的进程ID (PID)。像这样使用netstat:
netstat -a -n -p -l
这将打印如下内容:
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1879/sendmail: acce
tcp 0 0 0.0.0.0:21 0.0.0.0:* LISTEN 1860/xinetd
其中-a打印所有的套接字,-n显示端口号,-p显示PID, -l只显示正在监听的内容(这是可选的,取决于你想要什么)。
你想要的真实信息是PID。现在我们可以通过下面的操作关闭这个进程:
kill 1879
如果你要关闭一个服务,最好使用:
service sendmail stop
Kill实际上只是杀死了这个进程和它拥有的所有子进程。使用service命令运行init. conf中注册的关机脚本。d目录。如果你在一个服务上使用kill,它可能无法正常启动,因为你没有正确关闭它。这取决于服务。
不幸的是,Mac在这方面与Linux/Unix不同。你不能使用netstat。如果你对Mac感兴趣,请阅读本教程:
http://www.tech-recipes.com/rx/227/find-out-which-process-is-holding-which-socket-open/
如果你在Windows上使用TaskManager来杀死进程,使用services UI来关闭服务。你可以像Linux/Unix一样在Windows上使用netstat来识别PID。
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/netstat.mspx?mfr=true