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*   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'],
(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 ='pid')
subprocess.Popen(['kill', '-9', pid])

It can save quite a bit of time.


There are currently no comments

New Comment


required (not published)


Australia: 07 3103 2894

International: +61 410 545 357


RSS / Atom