Finding and killing processes on ports

I often have to develop server applications for clients and its easy, especially during development to have processes left around listening on ports. There is a slow way and a quick way to kill any such unwanted processes off.

The slow way to identify and kill a process on a port, which is fine for one off use, is to identify the process using netstat:

~ $ netstat -lpn | grep :1234
...
tcp 0  0 127.0.0.1:1234 0.0.0.0:*   LISTEN      7260/python   

Substitute 1234 for the port you are looking for. The process id is the number before the command line that created the process - 7260 in the above example.

Once you know the process id you can kill it off with:

~ $ kill -9 7260

This method can be pretty tedious, especially if you are prototyping or developing a collection of servers that work together that you often need to kill them off en mass. The following python snippet offers a quick way to find the processes and kill them all off in one go:

import os
import subprocess
import re

ports = ['1234','5678','9101']


popen = subprocess.Popen(['netstat', '-lpn'],
                         shell=False,
                         stdout=subprocess.PIPE)
(data, err) = popen.communicate()

pattern = "^tcp.*((?:{0})).* (?P[0-9]*)/.*$"
pattern = pattern.format(')|(?:'.join(ports))
prog = re.compile(pattern)
for line in data.split('\n'):
match = re.match(prog, line)
if match:
pid = match.group('pid')
subprocess.Popen(['kill', '-9', pid])

It can save quite a bit of time.


Comments

There are currently no comments

New Comment

required

required (not published)

optional

Australia: 07 3103 2894

International: +61 410 545 357

Feeds

RSS / Atom