16

Is it possible in python to kill a process that is listening on a specific port, say for example 8080?

I can do netstat -ltnp | grep 8080 and kill -9 <pid> OR execute a shell command from python but I wonder if there is already some module that contains API to kill process by port or name?

8 Answers 8

22

You could use the psutil python module. Some untested code that should point you in the right direction:

from psutil import process_iter
from signal import SIGTERM # or SIGKILL

for proc in process_iter():
    for conns in proc.connections(kind='inet'):
        if conns.laddr.port == 8080:
            proc.send_signal(SIGTERM) # or SIGKILL
8
  • 2
    I have "access denied" running this code. How to "sudo" proc.get_connections(kind='inet') ? Mar 31, 2015 at 21:03
  • why don't you run the whole thing with sudo in the first place?
    – Toote
    Mar 31, 2015 at 22:51
  • 1
    As far as I know, there is no way to do that that wouldn't be the same as running the script with sudo in the first place. If you can't kill it just like that it probably means that the process (the one you are trying to kill) was run with sudo or from a different user, so it needs to be killed using sudo or from that very same user
    – Toote
    Apr 1, 2015 at 19:48
  • 1
    redundant continue
    – v4gil
    Feb 17, 2019 at 22:02
  • 2
    Solution: Catch exception for processes for which you don't have permission. try: for conns in proc.connections(kind='inet'): ... except (PermissionError, psutil.AccessDenied): pass See stackoverflow.com/questions/19731665/…
    – Joshua M
    Mar 12, 2020 at 0:30
5

You could this with a subprocess and then kill it.

import os
import signal
from subprocess import Popen, PIPE

port = 1234
process = Popen(["lsof", "-i", ":{0}".format(port)], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
for process in str(stdout.decode("utf-8")).split("\n")[1:]:       
    data = [x for x in process.split(" ") if x != '']
    if (len(data) <= 1):
        continue

    os.kill(int(data[1]), signal.SIGKILL)
4

The simplest way to kill a process on a port is to use the python library: freeport (https://pypi.python.org/pypi/freeport/0.1.9) . Once installed, simply:

# install freeport
pip install freeport

# Once freeport is installed, use it as follows
$ freeport 3000
Port 3000 is free. Process 16130 killed successfully

The implementation details is available here: https://github.com/yashbathia/freeport/blob/master/scripts/freeport

3
  • @KardiTeknomo Do you have freeport library installed? I have added command to install freeport
    – YBathia
    Jul 2, 2018 at 14:58
  • yes, I installed freeport but it does not work. Killing the process manually using netstat -ano | findstr :8080 and taskkill /PID foundPID /F does much better job Jul 3, 2018 at 6:31
  • freeport uses lsof and due to that probably doesn't work on Windows. psutil from answer above is a cross-platform solution. Mar 7, 2019 at 15:50
4

I tried this method, it works for me..!

import os
import signal
import subprocess

command = "netstat -ano | findstr 8080"
c = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = c.communicate()
pid = int(stdout.decode().strip().split(' ')[-1])
os.kill(pid, signal.SIGTERM)
1
2

Another option is the killport python module. It'd be similar to freeport, but it uses psutil under the hood so it offers windows support as well

pip install killport

$ killport 3000
Killing:
❌ python3.7 (pid 47220) on port 3000
1

First of all, processes don't run on ports - processes can bind to specific ports. A specific port/IP combination can only be bound to by a single process at a given point in time.

As Toote says, psutil gives you the netstat functionality. You can also use os.kill to send the kill signal (or do it Toote's way).

0

A variation on the above solutions that I used:

import os
import signal
import subprocess

command = 'lsof -t -i:' + str(pid)
c = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = c.communicate()
if stdout == b'':
    return
pid = int(stdout.decode())
os.kill(pid, signal.SIGTERM)
0

For Linux, and if there is only one process using the port (can 2 processes even listen on the same port?)

import subprocess
from time import sleep

def kill_process_using_port(port):
    pid = subprocess.run(
        ['lsof', '-t', f'-i:{port}'], text=True, capture_output=True
    ).stdout.strip()
    if pid:
        if subprocess.run(['kill', '-TERM', pid]).returncode != 0:
            subprocess.run(['kill', '-KILL', pid], check=True)
        sleep(1)  # Give OS time to free up the PORT usage

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.