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?
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
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)
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
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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With