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

BashShell

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

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

I would do this instead :

PORT_NUMBER=1234
lsof -i tcp:${PORT_NUMBER} | awk 'NR!=1 {print $2}' | 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.

Solution 2 - Bash

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

2.) kill -9 processId

Solution 3 - Bash

kill $( lsof -i:6000 -t )

Or if you need permissions:

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

Solution 4 - Bash

Propose to use fuser command:

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

Solution 5 - Bash

sudo fuser -k 8080/tcp

An easy one to remember.

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

Solution 6 - Bash

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

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

Solution 7 - Bash

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

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

Replace 8864 by the port you want.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyliView Question on Stackoverflow
Solution 1 - BashShawn ChinView Answer on Stackoverflow
Solution 2 - BashthegruntView Answer on Stackoverflow
Solution 3 - BashDanSView Answer on Stackoverflow
Solution 4 - BashMichael ZarubinView Answer on Stackoverflow
Solution 5 - BashNVRMView Answer on Stackoverflow
Solution 6 - BashvmpstrView Answer on Stackoverflow
Solution 7 - BashShams NavedView Answer on Stackoverflow