Oneliner command to use kill given tcp port number instead of PID?
Solution 1:
fuser can do that:
sudo fuser -KILL -k -n tcp 8088
Solution 2:
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