How to find process id to kill the process running at a particular port? [duplicate]
I often do e.g.
sudo netstat -lpn |grep :8088
view the output
tcp6 0 0 :::8088 :::* LISTEN 11189/java
and then
sudo kill -kill 11189
I'd like to have a more convenient command exactly like killatport 8088
that uses the tcp port number as a variable and that I can make as an alias to a pipeline that does what I want, but how do I get the PID from the output and pipe it to the kill command? I suppose I might be able to use awk to get the PID from the output from netstat, but how do I safeguard and make an exact port match so that the input 80 won't match 8080 and likewise? Should I make it a C program instead? Or is there already a small utility like this?
fuser can do that:
sudo fuser -KILL -k -n tcp 8088
A command can be formulated like this:
netstat -lpn | grep ":1234\b" | awk '{sub(/\/.*/, "", $NF); print $NF}' | xargs -i kill -kill {}
Explanation:
-
netstat -ltpn
- This lists the listening ports (
l
) on TCP (t
) and their programs (p
) without resolving port numbers to names (n
).
- This lists the listening ports (
-
grep ":1234\b"
- This searches for
:1234
followed by a boundary (\b
), indicating the end of the word (or number, in our case). This makes sure that we don't catch:12345
for example.
- This searches for
-
awk '{sub(/\/.*/, "", $NF); print $NF}'
-
This
- substitutes
sub(/regex/,"replacewith", #fieldnumber)
- this regex
\/.*
- with nothing
""
- in the field
$NF
, which means the last field (i.e. the field that containsPID/program
) - then prints it
print $NF
.
The regex
\/.*
matches a literal/
and everything after it, and then we're replacing it with nothing, essentially deleting it, so we're left with only the PID number in that field. - substitutes
-
-
xargs -i kill -kill {}
-
xargs -i
is a program that allows you to make the output of the previous command act as the input to another command. Our command iskill -kill {}
where{}
indicates "the output from the previous command in the pipeline", which is our PID number.
-
Note: this whole command might be a little bit dangerous because you might accidentally kill something you didn't want to. It could use with a little bit more sanitization. Just make sure you get the correct port number when using it.
If you want to make this into a function, you can add the following to your ~/.bashrc
:
killatport(){
netstat -lpn | grep ":$1\b" | awk '{sub(/\/.*/, "", $NF); print $NF}' | xargs -i kill -kill {}
}
Save and apply the changes using source ~/.bashrc
. Now, you can use the function like this:
killatport 8088