- 4 Ways to Find Out What Ports Are Listening in Linux
- 1. Using Netstat Command
- 2. Using ss Command
- 3. Using Nmap Command
- 4. Using lsof Command
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- 3 Ways to Find Out Which Process Listening on a Particular Port
- 1. Using netstat Command
- 2. Using lsof Command
- 3. Using fuser Command
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Linux Find Out Which Process Is Listening Upon a Port
- Linux Find Out Which Process Is Listening Upon a Port
- Linux netstat command find out which process is listing upon a port
- A note about ss command
- Video demo
- fuser command
- Find Out Current Working Directory Of a Process
- Find Out Owner Of a Process on Linux
- lsof Command Example
- Help: I Discover an Open Port Which I Don’t Recognize At All
- Check For rootkit
- Keep an Eye On Your Bandwidth Graphs
- Conlcusion
- Найти процесс по номеру порта в Linux
- Пример использования netstat
- Пример использования fuser
- Пример использования lsof
4 Ways to Find Out What Ports Are Listening in Linux
The state of a port is either open, filtered, closed, or unfiltered. A port is said to be open if an application on the target machine is listening for connections/packets on that port.
In this article, we will explain four ways to check open ports and also will show you how to find which application is listening on what port in Linux.
1. Using Netstat Command
Netstat is a widely used tool for querying information about the Linux networking subsystem. You can use it to print all open ports like this:
The flag -l tells netstat to print all listening sockets, -t shows all TCP connections, -u displays all UDP connections and -p enables printing of application/program name listening on the port.
Check Open Ports Using Netstat Command
To print numeric values rather than service names, add the -n flag.
Show Numeric Values
You can also use grep command to find out which application is listening on a particular port, for example.
Find Port of Running Application
Alternatively, you can specify the port and find the application bound to, as shown.
Find Application Using a Port Number
2. Using ss Command
ss command is another useful tool for displaying information about sockets. It’s output looks similar to that of netstat. The following command will show all listening ports for TCP and UDP connections in numeric value.
Find Open Ports Using ss Command
3. Using Nmap Command
Nmap is a powerful and popular network exploration tool and port scanner. To install nmap on your system, use your default package manager as shown.
To scan all open/listening ports in your Linux system, run the following command (which should take a long time to complete).
4. Using lsof Command
The final tool we will cover for querying open ports is lsof command, which is used to list open files in Linux. Since everything is a file in Unix/Linux, an open file may be a stream or a network file.
To list all Internet and network files, use the -i option. Note that this command shows a mix of service names and numeric ports.
List Open Network Files Using lsof Command
To find which application is listening on a particular port, run lsof in this form.
Find Application Using Port
That’s all! In this article, we have explained four ways to check open ports in Linux. We also showed how to check which processes are bound upon particular ports. You can share your thoughts or ask any questions via the feedback 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.
Источник
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.
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.
Источник
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:
- netstat command or ss command – a command-line tool that displays network connections, routing tables, and a number of network interface statistics.
- fuser command – a command line tool to identify processes using files or sockets.
- 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.
- /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.
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
Источник
Найти процесс по номеру порта в 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-системах, и теперь у вас ни один порт не останется неопознанным!
Источник