Question

I run a lot of curl process through a script. These curl processes specify the local ports to be used. Now I need to kill some of these processes based on their local ports. For eg i want to kill the processes with the local ports lying between 30000 and 30100.

enter image description here

Now how do i kill only the processes with local ports between 30000 and 30100.

I believe i can write a perl script to parse the output and extract the values of the local port then kill the process satifying my conditions, but is there a way to do it with a single nested linux command, perhaps using awk?

Was it helpful?

Solution

You can do:

ps -aux | awk '$14>=30000 && $14<=30100 && $0~/curl/ { print $2 }' | xargs kill -9

Based on your screenshot, port values appear on 14th column ($14 holds this value), putting a check of $0~/curl/ grabs only those lines with curl effectively removing the need for grep. print $2 prints the process id. We then pipe the output to xargs and kill.

OTHER TIPS

You can use

kill  `lsof -i TCP@<your-ip-address>:30000-30100 -t`

to kill the processes attached to those ports, where <your-ip-address> must be the IP address that those connections use on the local side (this could be "localhost" or the external IP address of your host, depending).

If you leave the IP address out, you risk killing unrelated processes (that are connected to a destination port in the given range).

See this post for the background on lsof.

You can use the pkill command like so:

pkill -f -- 'curl.*local-port 30(0[0-9][0-9]|100)'

A less strict regular expression of course works, too, if you are sure you won't kill unrelated processes. You can do pgrep -fa -- <regexp> first to check if your regexp is correct, if you think that is necessary.

Note that matching number ranges is not one of the strengths of regular expressions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top