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

Viewed 21218

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

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)

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)

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

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)

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

Related