2

I have a process that listens on a TCP port (?0003). From time to time it crashes - badly. It stops working, but continues hogging the port for some time, so I can't even restart it. I'm looking to automate this.

What I do right now is:

netstat -ntlp |grep -P "\*\:\d0003"

To see what the PID is and then:

kill -9 <pid>

Does anyone have a script (or EXE for that matter) that would link the two steps together, ie. parse the PID from the first command and pass it to the second?

EMP
  • 5,172
  • 10
  • 37
  • 33

6 Answers6

5
kill $(netstat -ntpl 2>/dev/null | egrep "^tcp  .*:[0-9]0003"|awk '{print $7}'|cut -d / -f 1 )

You may do kill -9 instead of you think the -9 is required. I redirect the netstat stderr because it omits a message when run as non-root which is unimportant for this purpose. I include tcp in the regex to filter out tcp6.

Peter Lyons
  • 283
  • 3
  • 12
  • 2
    Using back-apostrophes is deprecated, because this leads to quoting-related problems and mistakes. Switch to `$()` and turn using it into a habit. –  Mar 15 '10 at 00:30
5

You also can do by that way :

kill -9 $( lsof -i:?0003 -t )
Deimosfr
  • 594
  • 2
  • 5
  • Very elegant! I often use things like lsof -ni:80,443 - but wasn`t aware of the switch -t thanks! – ThorstenS Mar 15 '10 at 06:33
  • Indeed. the `?` wildcard doesn't work on my version of lsof, but multiple -i options work. Changing the accepted answer to this one. – EMP Mar 15 '10 at 22:26
3

there you go, one line for you

netstat -ntlp | awk '$4~/:*0003$/{gsub(/\/.*/,"",$NF);cmd="kill -9 "$NF;system(cmd)}'
user37841
  • 341
  • 1
  • 2
  • +1 Works very nicely, thank you. I'm accepting Peter Lyons' answer, just because it's one line and can be pasted into the command-line more easily. :) – EMP Mar 15 '10 at 00:26
  • Alright then, another +1 here on Server Fault. – EMP Mar 15 '10 at 22:23
1

I take it that the python command is just the first term in the full command, right? If you have the name of the script being run you can look at something like pgrep -f

If you are sure of uniqueness, you can also use the related pkill -f

0

What about killall <command> are there more than one of these processes?

If that don't work try:

PID=`netstat -ntlp |grep -P "\*\:\d0003"`; kill -9 $PID

That should do the trick.

  • No, there's just one, and I can't go by the process name, because it's typically just "python" or "java". – EMP Mar 15 '10 at 00:05
0

Maybe the fuser command with the -k and -n options may help. Say "man fuser" for more info.