Linux проверить порт чем занят порт

How to check if a certain port is open and unused?

Could you please help and tell how can i find out if port 80 is open and unused so that I can start installation.

For what it’s worth, /etc/services is completely static. Grepping it can tell you if a port is officially designated by IANA or some such, but does not tell whether or not it’s in local use.

9 Answers 9

sudo netstat -anp | grep ':80 ' 

That should give you pid & name of the process that holds port 80

This can be achieved using the nc command as follows:

It will return TRUE if the port is already in use, or FALSE is it (i.e, available not listening currently).

I don’t recommend lsof or netstat method as it first try to scan all running PIDs to get all bounded ports:

# time lsof -i:8888 real 0m1.194s user 0m0.137s sys 0m1.056s``` # time nc -z 127.0.0.1 8888 real 0m0.014s user 0m0.011s sys 0m0.004s 

Here 8888 is an unused port. The nc command is ~85 times faster in the above example.

Eg 1:

$ nc -z 127.0.0.1 80 && echo "IN USE" || echo "FREE" IN USE $ nc -z 127.0.0.1 81 && echo "IN USE" || echo "FREE" FREE 

Eg 2:

If you are trying with a remote IP, it is better to add a timeout to auto-exit if it is not accepting connection for the specified time.

Its Google’s IP which is not used, so it will timeout after trying for 2 seconds.

This also works greatly when running inside the Docker image that uses host network. Inside the image, lsof incorrectly reports the port is not in use when it actually is.

The traditional version of nc does not include the -z option. See the differences between traditional and openbsd.

netstat -tln | tail -n +3 | awk '< print $4 >' 

This one displays bind addresses of TCP listening endpoints. All other endpoints are free; Also if on Unix and you are not root, then you can’t bind to a ‘privileged’ port number (port number lower than 1024).

Explained in more details:

  • netstat -tln — all listening tcp ports
  • tail -n +3 — cut off the header of netstat command
  • awk ‘< print $4 >‘ — print the fourth column that consists of [ip]:[port]
Читайте также:  Драйверы linux nvidia asus

For the general case you still need to care to cut out all irrelevant interfaces; a listening address 0.0.0.0 is listening on all network cards, if there is an IP address then that’s the specific IP of the network card/network interface.

Источник

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.

$ sudo apt-get install net-tools [On Debian/Ubuntu & Mint] $ sudo dnf install net-tools [On CentOS/RHEL/Fedora and Rocky Linux/AlmaLinux] $ pacman -S netstat-nat [On Arch Linux] $ emerge sys-apps/net-tools [On Gentoo] $ sudo dnf install net-tools [On Fedora] $ sudo zypper install net-tools [On openSUSE]

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.

$ sudo apt-get install lsof [On Debian, Ubuntu and Mint] $ sudo yum install lsof [On RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux] $ sudo emerge -a sys-apps/lsof [On Gentoo Linux] $ sudo pacman -S lsof [On Arch Linux] $ sudo zypper install lsof [On OpenSUSE]

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:

$ sudo apt-get install psmisc [On Debian, Ubuntu and Mint] $ sudo yum install psmisc [On RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux] $ sudo emerge -a sys-apps/psmisc [On Gentoo Linux] $ sudo pacman -S psmisc [On Arch Linux] $ sudo zypper install psmisc [On OpenSUSE]

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

Читайте также:  Узнать какие драйвера используются linux

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

$ ps -p 2053 -o comm= $ ps -p 2381 -o comm=

Find Port and Process ID in Linux

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

You might also like:

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.

Источник

Кто слушает порт в Linux

Открытый доступ к порту хоть и является угрозой безопасности системы, но по сути ничего плохого не представляет до тех пор, пока его не начинает использовать программа. А чтобы выяснить какая программа слушает какой порт можно использовать утилиты «netstat» (или «ss») и «lsof».

Чтобы узнать информацию о программе, которая прослушивает определённый порт, можно воспользоваться командой «lsof» со следующими ключами:

Здесь «номер_порта» — это цифра.

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

$: sudo lsof -i :53 COMMAND PID USER TYPE NODE NAME systemd-r 818 systemd-resolve IPv4 UDP localhost:domain systemd-r 818 systemd-resolve IPv4 TCP localhost:domain (LISTEN)

Но рекомендуем чаще запускать команду для получения списка программ, которые используют какие-либо tcp/udp порты. В этом помогает «netstat» или «ss»:

  • -l показать только прослушиваемые «LISTEN» порты.
  • -n показывать адреса как ip, а не пытаться определять домены.
  • -t показывать TCP порты.
  • -u показывать UDP порты.
  • -p показать название программы, которая слушает порт.
$: sudo netstat -lntup Prt Local Addr State PID/Program tcp 0.0.0.0:443 LISTEN 204/nginx tcp 0.0.0.0:80 LISTEN 202/nginx tcp 0.0.0.0:22 LISTEN 174/sshd udp 127.0.0.1:323 233/chronyd

По результату можно заметить какая программа прослушивает какой порт. Если ip в секции «Local Address» равен «127.0.0.1», то это локальное обращение. Такой порт можно не закрывать фаерволом — он и так не будет доступен извне. Но ip с нулями «0.0.0.0» говорят о том, что программа слушает все адреса. То есть она примет любой запрос, в том числе внешний.

Источник

Проверка занятости порта сервисом в Linux

Oct 4, 2018 06:09 · 637 words · 3 minute read lsof netstat fuser tips

Однажды вам обязательно понадобится проверить используемый порт определенного сервиса (или наоборот, найти сервисы, слушающие конкретный порт) — в Linux существует несколько утилит командной строки, которые могут с этим помочь. Давайте разберемся!

Первым делом на ум приходит утилита netstat , с помощью которой можно проверить сетевые соединения, статистику сетевых интерфейсов, таблицу маршрутизации и т. д.

Устанавливается данная утилита в разных дистрибутивах по-разному, например, для RedHat и CentOS:

sudo yum install net-tools 
sudo apt-get install net-tools 

Для вывода детальной информации о всех TCP и UDP ендпоинтах можно воспользоваться следующей командой:

Читайте также:  Linux bash проверка существования директории

Вывод будет примерно следующим:

Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 1323/systemd-resolv tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1661/sshd tcp 0 0 127.0.0.1:17123 0.0.0.0:* LISTEN 1753/python tcp6 0 0 . 31341 . * LISTEN 30068/java tcp6 0 0 . 22222 . * LISTEN 30068/java tcp6 0 0 . 80 . * LISTEN 30068/java tcp6 0 0 . 10769 . * LISTEN 126755/docker-proxy tcp6 0 0 . 10770 . * LISTEN 129459/docker-proxy tcp6 0 0 . 10771 . * LISTEN 129540/docker-proxy tcp6 0 0 . 10772 . * LISTEN 130172/docker-proxy tcp6 0 0 . 10773 . * LISTEN 130187/docker-proxy tcp6 0 0 . 10774 . * LISTEN 130545/docker-proxy tcp6 0 0 . 22 . * LISTEN 1661/sshd tcp6 0 0 . 10775 . * LISTEN 7406/docker-proxy 
  • -p — вывод ID процесса и его имени;
  • -n — вывод адресов;
  • -l — вывод сокетов;
  • -t — вывод TCP соединений;
  • -u — вывод UDP соединений.

Найти сервис, запущенный на определенном порту можно так:

Аналогично можно найти на каком порту запущен определенный сервис:

netstat -pnltu | grep -i "sshd" 

Также для наших целей подойдет утилита командной строки fuser . По умолчанию она не установлена в большинстве операционных систем, чтобы установить ее в Centos/RedHat делаем так:

Например, чтобы найти идентификаторы процессов (PIDs), запущенных на 80-м порту, выполняем команду:

Результат выполнения будет примерно следующим:

Далее можем найти имя процесса по его идентификатору (PID):

Еще один способ — использование утилиты lsof . Установка ее в RedHat/CentOS выглядит так:

Вывод всех активных TCP и UPD соединений:

Результатом будет примерно следующее:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd-r 1323 systemd-resolve 12u IPv4 20197 0t0 UDP 127.0.0.53:domain systemd-r 1323 systemd-resolve 13u IPv4 20198 0t0 TCP 127.0.0.53:domain (LISTEN) sshd 1661 root 3u IPv4 29741 0t0 TCP *:ssh (LISTEN) sshd 1661 root 4u IPv6 29743 0t0 TCP *:ssh (LISTEN) python 1754 dd-agent 4u IPv6 39499 0t0 UDP localhost.localdomain:8125 docker-pr 7406 root 4u IPv6 287933991 0t0 TCP *:10775 (LISTEN) docker-pr 7459 root 4u IPv6 287906596 0t0 TCP *:10776 (LISTEN) docker-pr 7792 root 4u IPv6 287937795 0t0 TCP *:10777 (LISTEN) docker-pr 8435 root 4u IPv6 287955267 0t0 TCP *:10778 (LISTEN) docker-pr 8447 root 4u IPv6 287915222 0t0 TCP *:10779 (LISTEN) docker-pr 9060 root 4u IPv6 287891442 0t0 TCP *:10780 (LISTEN) docker-pr 9429 root 4u IPv6 287957044 0t0 TCP *:10781 (LISTEN) docker-pr 9463 root 4u IPv6 287921075 0t0 TCP *:10782 (LISTEN) ntpd 10594 ntp 16u IPv6 35365570 0t0 UDP *:ntp 

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

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME sshd 1661 root 3u IPv4 29741 0t0 TCP *:ssh (LISTEN) sshd 1661 root 4u IPv6 29743 0t0 TCP *:ssh (LISTEN) 

Напоследок можно также воспользоваться утилитой whatportis . Ее установка в RedHat/Centos требует чуть больше действий:

yum install python34-setuptools 

В Debian/Ubuntu все гораздо проще:

В общем виде использование утилиты выглядит так:

whatportis [номер_порта | имя_сервиса] 

Если вам неизвестно точное имя сервиса, можно воспользоваться опцией —like , например:

Также доступен вывод информации в json-формате:

Источник

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