Linux search process by port

Найти процесс по номеру порта в Linux

При работе в Unix-системах мне частенько приходится определять, какой процесс занимает порт, например, чтобы остановить его и запустить на нём другой процесс. Поэтому я решил написать эту небольшую статью, чтоб каждый, прочитавший её, мог узнать, каким процессом занят порт в Ubuntu, CentOS или другой ОС из семейства Linux.

Как же вычислить, какие запущенные процессы соотносятся с занятыми портами? Как определить, что за процесс открыл udp-порт 2222, tcp-порт 7777 и т.п.? Получить подобную информацию мы можем нижеперечисленными методами:

netstat утилита командной строки, показывающая сетевые подключения, таблицы маршрутизации и некоторую статистику сетевых интерфейсов; fuser утилита командной строки для идентификации процессов с помощью файлов или сокетов; lsof утилита командной строки, отображающая информацию об используемых процессами файлах и самих процессах в UNIX-системе; /proc/$pid/ в ОС Linux /proc для каждого запущенного процесса содержит директорию (включая процессы ядра) в /proc/$PID с информацией об этом процессе, в том числе и название процесса, открывшего порт.

Использование вышеперечисленных способов может потребовать права супер-пользователя.

Теперь давайте рассмотрим каждый из этих способов по отдельности.

Пример использования netstat

Введём в командную строку команду:

Получим примерно такой результат:

Из вывода видно, что 4942-й порт был открыт Java-приложением с PID’ом 3413. Проверить это можно через /proc :

Примерный результат выполнения команды:

При необходимости получения информации по конкретному порту (например, 80-му, используемого обычно для HTTP) вместо отображения всей таблицы можно grep -ануть результат:

Результат будет примерно такой:

Пример использования fuser

Для того, чтобы вычислить процесс, занимающий порт 5050, введём команду:

И получим результат:

Аналогичным образом, как мы делали выше, можно посмотреть процесс в его директории /proc/$PID , в которой можно найти много интересной дополнительной информации о процессе, такую как рабочая директория процесса, владелец процесса и т.д., но это выходит за рамки этой статьи.

Пример использования lsof

При использовании lsof введите команду по одному из шаблонов:

Пример реального использования:

После этого мы можем получить более полную информацию о процессах с PID’ами 2123, 2124 и т.д..

На выходе получим примерно следующее:

Получить информацию о процессе также можно следующим проверенным способом:

В этом выводе можно выделить следующие параметры:

  • 2727 — PID;
  • www-date — имя пользователя владельца;
  • www-date — название группы;
  • /usr/sbin/apache2 -k start — название команды с аргументами;
  • 14:27:33 — время работы процесса в формате [[дд-]чч:]мм:сс;
  • Mon Nov 30 21:21:28 2015 — время старта процесса.

Надеюсь, у меня получилось доступно объяснить, как определить процесс по порту в Linux-системах, и теперь у вас ни один порт не останется неопознанным!

Источник

Linux Find Out Which Process Is Listening Upon a Port

Linux Find Out Which Process Is Listening Upon a Port

You can the following programs to find out about port numbers and its associated process:

  1. netstat command or ss command – a command-line tool that displays network connections, routing tables, and a number of network interface statistics.
  2. fuser command – a command line tool to identify processes using files or sockets.
  3. lsof command – a command line tool to list open files under Linux / UNIX to report a list of all open files and the processes that opened them.
  4. /proc/$pid/ file system – Under Linux /proc includes a directory for each running process (including kernel processes) at /proc/PID, containing information about that process, notably including the processes name that opened port.
Читайте также:  Dual sim windows mobile

You must run above command(s) as the root user.

Linux netstat command find out which process is listing upon a port

Type the following command:
# netstat -tulpn
Sample outputs:

TCP port 3306 was opened by mysqld process having PID # 1138. You can verify this using /proc, enter:
# ls -l /proc/1138/exe
Sample outputs:

You can use grep command or egrep command to filter out information:
# netstat -tulpn | grep :80
Sample outputs:

A note about ss command

Some Linux distro considered the nestat command as deprecated and therefore should be phased out in favor of more modern replacements such as ss command. The syntax is:
$ sudo ss -tulpn
$ sudo ss -tulpn | grep :3306

Click to enlarge image

Video demo

fuser command

Find out the processes PID that opened tcp port 7000, enter:
# fuser 7000/tcp
Sample outputs:

Finally, find out process name associated with PID # 3813, enter:
# ls -l /proc/3813/exe
Sample outputs:

/usr/bin/transmission is a bittorrent client, enter:
# man transmission
OR
# whatis transmission
Sample outputs:

Find Out Current Working Directory Of a Process

To find out current working directory of a process called bittorrent or pid 3813, enter:
# ls -l /proc/3813/cwd
Sample outputs:

OR use pwdx command, enter:
# pwdx 3813
Sample outputs:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Find Out Owner Of a Process on Linux

Use the following command to find out the owner of a process PID called 3813:
# ps aux | grep 3813
OR
# ps aux | grep ‘[3]813’
Sample outputs:

OR try the following ps command:
# ps -eo pid,user,group,args,etime,lstart | grep ‘[3]813’
Sample outputs:

Another option is /proc/$PID/environ, enter:
# cat /proc/3813/environ
OR
# grep —color -w -a USER /proc/3813/environ
Sample outputs (note –colour option):

Fig.01: grep output

lsof Command Example

Type the command as follows:

Now, you get more information about pid # 1607 or 1616 and so on:
# ps aux | grep ‘[1]616’
Sample outputs:
www-data 1616 0.0 0.0 35816 3880 ? S 10:20 0:00 /usr/sbin/apache2 -k start
I recommend the following command to grab info about pid # 1616:
# ps -eo pid,user,group,args,etime,lstart | grep ‘[1]616’
Sample outputs:

  • 1616 : PID
  • www-date : User name (owner – EUID)
  • www-date : Group name (group – EGID)
  • /usr/sbin/apache2 -k start : The command name and its args
  • 03:16:22 : Elapsed time since the process was started, in the form [[dd-]hh:]mm:ss.
  • Fri Oct 29 10:20:17 2010 : Time the command started.

Help: I Discover an Open Port Which I Don’t Recognize At All

The file /etc/services is used to map port numbers and protocols to service names. Try matching port numbers:
$ grep port /etc/services
$ grep 443 /etc/services
Sample outputs:

Check For rootkit

I strongly recommend that you find out which processes are really running, especially servers connected to the high speed Internet access. You can look for rootkit which is a program designed to take fundamental control (in Linux / UNIX terms “root” access, in Windows terms “Administrator” access) of a computer system, without authorization by the system’s owners and legitimate managers. See how to detecting / checking rootkits under Linux.

Keep an Eye On Your Bandwidth Graphs

Usually, rooted servers are used to send a large number of spam or malware or DoS style attacks on other computers.

Conlcusion

You learned various Linux commands to find information about running process and their ports. See the following man pages for more information:
$ man ps
$ man grep
$ man lsof
$ man netstat
$ man fuser

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

3 Ways to Find Out Which Process Listening on a Particular Port

A port is a logical entity that represents an endpoint of communication and is associated with a given process or service in an operating system. In previous articles, we explained how to find out the list of all open ports in Linux and how to check if remote ports are reachable using the Netcat command.

Читайте также:  Интерфейс пользователя windows обеспечение

In this short guide, we will show different ways of finding the process/service listening on a particular port in Linux.

1. Using netstat Command

netstat (network statistics) command is used to display information concerning network connections, routing tables, interface stats, and beyond. It is available on all Unix-like operating systems including Linux and also on Windows OS.

In case you do not have it installed by default, use the following command to install it.

Once installed, you can use it with the grep command to find the process or service listening on a particular port in Linux as follows (specify the port).

Check Port Using netstat Command

In the above command, the flags.

  • l – tells netstat to only show listening sockets.
  • t – tells it to display tcp connections.
  • n – instructs it to show numerical addresses.
  • p – enables showing of the process ID and the process name.
  • grep -w – shows matching of exact string (:80).

Note: The netstat command is deprecated and replaced by the modern ss command in Linux.

2. Using lsof Command

lsof command (List Open Files) is used to list all open files on a Linux system.

To install it on your system, type the command below.

To find the process/service listening on a particular port, type (specify the port).

Find Port Using lsof Command

3. Using fuser Command

fuser command shows the PIDs of processes using the specified files or file systems in Linux.

You can install it as follows:

You can find the process/service listening on a particular port by running the command below (specify the port).

Then find the process name using PID number with the ps command like so.

Find Port and Process ID in Linux

You can also check out these useful guides about processes in Linux.

That’s all! Do you know of any other ways of finding the process/service listening on a particular port in Linux, let us know via the comment form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Which Linux process is using a particular network port?

Most network related services have to open up a network socket, so they can start listening for incoming network requests. It is common to find the TCP or UDP being used as the main communication protocol. In this article, we will check what ports are used by which Linux process.

Table of Contents

Auditing processes and network services

Find out what process is listening to a port

Only one process can actively listen to a TCP or UDP port. We usually only discover this when another process is already running on a specific port, while we try to start another service:

[emerg] 9400#0: bind() to 0.0.0.0:80 failed (98: Address already in use)

or something like:

Time to tackle which process is keeping these addresses or ports in use!

Using lsof to show open files and network ports

Let’s start with a powerful utility named lsof. It is not always installed by default, but still a very common utility. Its name is derived from listing open files. In Linux, even a network socket is a file. So this is definitely the right utility to retrieve some useful information. LSOF will include network-related data like port numbers and process names.

To find open ports and the related processes, ask lsof to see the related details. We filter out all UDP ports and only want to see TCP ports that are listening to data.

Читайте также:  Драйверы для usb устройств linux

This output might look something like this:

LSOF displaying UDP ports and TCP ports in LISTEN state

This commands includes all UDP ports and for TCP only the ports which are actually in “LISTEN” state. Perfect to determine which process is listening to what port (or ports).

Note: Although egrep is getting deprecated, you can still use it. Or use ‘grep -E’ instead.

If you are interested in a particular port, lsof can filter by protocol and port number.

Using netstat to show ports and applications

The netstat utility is most likely the easiest way to determine what processes are running and what port they listen to. It is available on most systems by default.

The result might be looking something like this:

Netstat showing all running processes and ports they listen to

In this output, we see the following details:

  • Column 1: Proto
  • Column 2: Recv-Q
  • Column 3: Send-Q
  • Column 4: Local Address
  • Column 5: Foreign Address
  • Column 6: State
  • Column 7: PID/Program name

The protocol (Proto) defines the data transfer protocol. This is typically tcp or udp for IPv4, tcp or udp6 for IPv6. The Recv-Q and Send-Q are the queues to for receiving or sending data. In the output they are usually zero unless a transfer occurs at that moment. The Local Address field specifies the IP address with the related port number. Can listen to a particular IP address (like localhost or 127.0.0.1) or on all interfaces (0.0.0.0 for IPv4). This is usually the interesting part to filter out (tip: use grep). The State column is usually showing LISTEN for TCP. Then finally the PID/Program name column shows the actual process that is listening to a particular network port.

Using the ss command

f you don’t have the netstat utility available, it might have been replaced with a newer toolkit. In that case, you usually have the ss utility available (iproute2 package).

To use the ss tool to see on Linux which ports are used by a particular process:

This will show a similar output. It shows all the listening ports, limited to UDP/TCP only, not translated to hostnames to speed up the results.

Detecting network ports for new processes

Sometimes you might be running a new process and not aware of any network ports being opened. This might occur when it just quickly happens, or due to a port listening conflict. Also when running services in containers, it might be harder to know what ports need to be opened, to get it fully functioning.

In these cases, the strace utility is of great help. It can track a running or new process and alert for any events of your interest. To track the open request of a network port, we can monitor the related system call (syscall), which is ‘bind’.

With this command we will see quickly after execution the following line:

This means it tried to open a network socket with port 80. Unfortunately, it does not show if it opens a TCP or UDP port. If we broaden the system calls a little bit, this information becomes available:

strace -f -e trace=network nc -lu 80
socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP) = 3
setsockopt(3, SOL_SOCKET, SO_REUSEADDR, [1], 4) = 0
bind(3, , 16) = 0

Conclusion

That’s it for today. Linux systems are very versatile, yet sometimes need the right tool to dig into the details you want to know. With tools like lsof, netstat, ss, and strace, we can find exactly the network information we are looking for.

Did this article help you or have a good one-liner for other readers? Share your comments to make this article even better!

Keep learning

So you are interested in Linux security? Join the Linux Security Expert training program, a practical and lab-based training ground. For those who want to become (or stay) a Linux security expert.

Run automated security scans and increase your defenses. Lynis is an open source security tool to perform in-depth audits. It helps with system hardening, vulnerability discovery, and compliance.

Источник

Оцените статью