Kill Processes by Port

By Michele Berardi
Picture of the author
Published on
image alt attribute

Kill Processes by Port Using Python

Introduction

Dealing with processes that hog important ports can be a nuisance, especially for developers working on web applications. This Python script comes to the rescue by using the psutil library to find and kill processes listening on a specified port, including their child processes. It's a handy tool when you need to free up a port that is occupied by a process that shouldn't be running.

Requirements

  • Python 3.6 or higher
  • psutil library

Installing psutil

To install the psutil library, run:

pip install psutil

Usage

To use the script:

  1. Modify the port_to_kill variable in the script to the port number you want to free up.
  2. Run the script:
    python kill_processes_by_port.py
    

The script will locate and terminate processes listening on the specified port along with their child processes. It will also provide details about the terminated processes, such as their Process ID (PID) and name.

Example

Here's a simple example that kills processes on port 8080:

port_to_kill = 8080
if kill_processes_by_port(port_to_kill):
    print(f"Killed processes on port {port_to_kill}")
else:
    print(f"No processes found on port {port_to_kill}")

Note

Be aware that terminating a process with this script might require administrative privileges, especially if the process is running under a different user or root. If you encounter a permission error, consider running the script with administrative privileges, like using sudo on Linux systems.

Conclusion

This Python script is a powerful tool for developers and system administrators who need to quickly free up ports occupied by lingering processes. It automates a typically manual and time-consuming task, simplifying workflow and increasing productivity.

For more details and the full script, visit the GitHub repository: Kill Processes by Port.

Stay Tuned

Want to become a AI pro?
The best articles, links and news related to AI delivered once a week to your inbox.