Find Which Process Listening on a Port on Debian 11 – Easy Ways

Posted on

Find Which Process Listening on a Port on Debian 11 - Easy Ways

Find Which Process Listening on a Port on Debian 11 – Easy Ways

This tutorial aims to guide you through 4 Ways to Find Which Process Listening on a Port on Debian 11. You can utilize the following Linux commands to identify the process or service that is actively listening on a specific port. Knowing which process is using a particular port is crucial for troubleshooting network issues, identifying potential conflicts, and ensuring that your services are running correctly.

To Find Which Process Listening on a Port on Debian 11, you’ll need access to your server as a non-root user with sudo privileges. If you haven’t already configured this, you can refer to a guide on Initial Server Setup with Debian 11.

Method 1 – Check for a Listening Port with netstat Command

The netstat tool is a classic utility used for displaying network connection information. It should be available on most Debian 11 systems. If it’s not present, you can easily install it using the following command:

sudo apt install net-tools -y

Now, you can use the following netstat command to check all the processes listening on various ports:

sudo netstat -tulpn

This command uses the following options:

  • -t: Displays TCP connections.
  • -u: Displays UDP connections.
  • -l: Shows only listening sockets.
  • -p: Displays the PID and program name.
  • -n: Displays numerical addresses and port numbers.

To pinpoint a specific port, you can pipe the output of netstat to the grep command. For example, to Find Which Process Listening on a Port on Debian 11, specifically port 80, you can execute the following command:

sudo netstat -tulpn | grep :80

Method 2 – Display Listening Ports with ss Command on Debian 11

Another way to Find Which Process Listening on a Port on Debian 11 is by using the ss command. In some Linux distributions, the netstat command is being deprecated, and ss is often preferred as a replacement. The ss command should be installed by default on Debian 11.

To check all processes using ss, use the following command:

sudo ss -tulpn

The options are similar to netstat:

  • -t: TCP sockets
  • -u: UDP sockets
  • -l: Listening sockets
  • -p: Process name
  • -n: Numerical addresses

To find a particular port, such as port 80, using the ss command, you can use:

sudo ss -tulpn | grep :80

Method 3 – Use lsof Command to Find Which Process Listening on a Port

The lsof command (list open files) is used to list all open files on a Linux system. This command should be available on your Debian 11 system by default. If it’s not, you can install it using the following command:

sudo apt install lsof -y

To get a full list of open files, you can run the command:

sudo lsof

This will generate a large amount of output. To Find Which Process Listening on a Port on Debian 11, you can filter the output to a specific port, such as port 80, using:

sudo lsof -i :80

The -i option specifies an internet address.

Method 4 – Check Listening Ports with the fuser command on Debian 11

Yet another way to Find Which Process Listening on a Port on Debian 11, is to use the fuser command. The fuser command identifies processes using specified files or file systems. You can install the fuser command on Debian 11 using the command:

sudo apt install psmisc -y

To find the process using a particular port, for example, port 80, you can run:

sudo fuser 80/tcp

The usage and options of the fuser command are:

Usage: fuser [-fIMuvw] [-a|-s] [-4|-6] [-c|-m|-n SPACE]
             [-k [-i] [-SIGNAL]] NAME...
       fuser -l
       fuser -V
Show which processes use the named files, sockets, or filesystems.

  -a,--all              display unused files too
  -i,--interactive      ask before killing (ignored without -k)
  -I,--inode            use always inodes to compare files
  -k,--kill             kill processes accessing the named file
  -l,--list-signals     list available signal names
  -m,--mount            show all processes using the named filesystems or
                        block device
  -M,--ismountpoint     fulfill request only if NAME is a mount point
  -n,--namespace SPACE  search in this name space (file, udp, or tcp)
  -s,--silent           silent operation
  -SIGNAL               send this signal instead of SIGKILL
  -u,--user             display user IDs
  -v,--verbose          verbose output
  -w,--writeonly        kill only processes with write access
  -V,--version          display version information
  -4,--ipv4             search IPv4 sockets only
  -6,--ipv6             search IPv6 sockets only
  -                     reset options

  udp/tcp names: [local_port][,[rmt_host][,[rmt_port]]]

Alternative Methods to Find Which Process Listening on a Port on Debian 11

While the above methods are effective, here are two alternative approaches:

1. Using systemd-socket-activate:

systemd-socket-activate is part of the systemd suite and can be used to manage socket activation. While it doesn’t directly show which process is listening, it can reveal which service will be started when a connection is made to a specific port, which indirectly helps identify the relevant process.

Explanation: systemd socket activation allows services to be started on-demand when a connection is made to a specific socket (port). Systemd listens on the socket and starts the service only when needed. This can save resources. We can query systemd to see which service is associated with a particular port.

Since systemd is the init system on Debian 11, this is a viable approach.

First, check if the service is socket-activated:

systemctl list-sockets

This will list all the active sockets and the services associated with them. Look for the port you are interested in.

If the service is socket-activated, you can then check the service definition to understand which executable will be run.

Example:

Let’s say systemctl list-sockets shows that port 80 is associated with apache2.socket. You can then examine the apache2.socket and apache2.service files to understand how Apache is configured to handle requests on port 80. These files are typically located in /lib/systemd/system/ or /etc/systemd/system/.

While this doesn’t directly give the PID like the other methods, it points you to the relevant service configuration, which then allows you to identify the process. You might then use ps aux | grep apache2 to find the PID.

2. Using Python’s psutil library:

Python provides a powerful library called psutil (process and system utilities) that can be used to gather information about running processes, including network connections.

Explanation: psutil offers a cross-platform way to access system information, including process details and network connections. You can write a Python script to iterate through all processes and their open connections, filtering for the desired port.

First, install psutil:

sudo apt install python3-pip
pip3 install psutil

Then, create a Python script (e.g., port_finder.py) with the following code:

import psutil

def find_process_by_port(port):
    """Finds the process listening on the specified port."""
    processes = []
    for proc in psutil.process_iter(['pid', 'name', 'connections']):
        try:
            for conn in proc.info['connections']:
                if conn.laddr.port == port and conn.status == 'LISTEN':
                    processes.append(proc.info)
                    break  # Found the port, no need to check other connections of this process
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass # Handle cases where the process disappears or access is denied

    return processes

if __name__ == "__main__":
    port_to_find = 80 # Change this to the port you want to find
    listening_processes = find_process_by_port(port_to_find)

    if listening_processes:
        print(f"Processes listening on port {port_to_find}:")
        for process in listening_processes:
            print(f"  PID: {process['pid']}, Name: {process['name']}")
    else:
        print(f"No process found listening on port {port_to_find}.")

Run the script:

sudo python3 port_finder.py

This script will iterate through all running processes and print the PID and name of any process listening on the specified port (80 in this example). Remember to run the script with sudo to overcome potential permission issues accessing process information.

Conclusion

At this point, you have learned 4 Ways to Find Which Process Listening on a Port on Debian 11, including the netstat, ss, lsof, and fuser commands. You can utilize these Linux commands to identify all processes or a particular process associated with a given port. In addition, you have explored two alternative methods using systemd-socket-activate and a Python script with psutil. These methods offer flexibility and can be adapted to various situations.

Hopefully, you found this guide helpful. You may also be interested in these articles:

  • Check HTTPS Port 443 is Open on Linux
  • Open and Close Ports with FirewallD on Rocky Linux 8
  • Check whether Port 25 is Open or Not on Linux

Leave a Reply

Your email address will not be published. Required fields are marked *