bash 如何根据端口查找进程并将它们全部杀死?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5043808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:12:13  来源:igfitidea点击:

How to find processes based on port and kill them all?

bashshell

提问by yli

Find processes based on port number and kill them all.

根据端口号查找进程并将它们全部杀死。

ps -efl | grep PORT_NUMBER | kill -9 process_found_previously

how to complete the last column?

如何完成最后一栏?

回答by Shawn Chin

The problem with ps -efl | grep PORT_NUMBERis that PORT_NUMBERmay match other columns in the output of psas well (date, time, pid, ...). A potential killing spree if run by root!

问题ps -efl | grep PORT_NUMBER在于它PORT_NUMBER也可能匹配输出中的其他列ps(日期、时间、pid 等)。如果由 root 运行,潜在的杀戮狂潮!

I would do this instead :

我会这样做:

PORT_NUMBER=1234
lsof -i tcp:${PORT_NUMBER} | awk 'NR!=1 {print }' | xargs kill 

Breakdown of command

命令分解

  • (lsof -i tcp:${PORT_NUMBER}) -- list all processes that is listening on that tcp port
  • (awk 'NR!=1 {print $2}') -- ignore first line, print second column of each line
  • (xargs kill) -- pass on the results as an argument to kill. There may be several.
  • ( lsof -i tcp:${PORT_NUMBER}) -- 列出在该 tcp 端口上侦听的所有进程
  • ( awk 'NR!=1 {print $2}') -- 忽略第一行,打印每行的第二列
  • ( xargs kill) - 将结果作为参数传递给kill. 可能有几个。

回答by thegrunt

1.) lsof -w -n -i tcp:8080

1.) lsof -w -n -i tcp:8080

2.) kill -9 processId

2.) kill -9 processId

回答by Michael Zarubin

Propose to use fuser command:

建议使用 fuser 命令:

fuser -k -TERM -n tcp ${PORT_NUMBER}

回答by DanS

kill $( lsof -i:6000 -t )

Or if you need permissions:

或者,如果您需要权限:

sudo kill $( sudo lsof -i:6000 -t )

回答by NVRM

sudo fuser -k 8080/tcp

须藤热熔器 -k 8080/tcp

An easy one to remember.

一个容易记住的。

This syntax is probably much more recent than the date of the question!

此语法可能比问题的日期更新得多!

回答by vmpstr

... | awk '{ print  }' | xargs kill -9

please test with "echo" instead of "kill" before running

请在运行前使用“echo”而不是“kill”进行测试

回答by Shams Naved

To kill all processes listening on a particular port, e.g. port 8864

杀死侦听特定端口的所有进程,例如端口 8864

kill -9 $ \`lsof -i:8864 -t\`

Replace 8864 by the port you want.

将 8864 替换为您想要的端口。