Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 924
Damir Avatar asked Dec 19 '13 20:12

Damir


5 Answers

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
like image 107
Toote Avatar answered Nov 11 '22 18:11

Toote


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)
like image 5
Jop Knoppers Avatar answered Nov 11 '22 18:11

Jop Knoppers


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

like image 4
YBathia Avatar answered Nov 11 '22 17:11

YBathia


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)
like image 3
Gowtham Balusamy Avatar answered Nov 11 '22 18:11

Gowtham Balusamy


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).

like image 1
Henrik Avatar answered Nov 11 '22 18:11

Henrik