Каким приложением занят порт linux

How to find ports opened by process ID in Linux?

Hmm..I don’t seem to have the —all and —program options. I’m using OSX. Brew doesn’t seem to have a formula for it either.

-n will dramatically speed things up by not resolving hostnames. netsta -tupan is a good default command all and easy to remember.

You can use the command below:

As a side note, netstat -ao will read the /proc/PID/tcp etc to see the ports opened by the process. This means that its reading information supplied by the system (the linux KERNEL), and is in no way directly looking on the network interface or other means. Same goes for lsof.

If you are doing this as a security measure, you failed. You should never (NEVER EVER) trust the output of netstat, even if you are 100% sure you are in fact running a real netstat program (as opposed to a trojaned version) or any other program that reads the /proc filesystem. Some people seem to think that netstat, ls, ps or any other of the standard unix tools do some sort of magic and poll information from the sources, the truth is all of them rely on the /proc filesystem to get all of their data, which can be easily subverted by a rootkit or hypervisor.

If you’re dealing with a rootkitted system or a compromised hypervisor, you can’t trust anything, including something that purports to look directly at the network interface.

You can use the netstat command line tool with the -p command line argument:

-p (Linux):

Process: Show which processes are using which sockets (similar to -b under Windows). You must be root to do this.

To display all ports open by a process with id $PID :

In some embedded devices or with old version of Linux, the problem is netstat do not have —process or -p options available.

The following script shows process with its IP and port, you must be root.

#!/bin/bash for protocol in tcp udp ; do #echo "protocol $protocol" ; for ipportinode in `cat /proc/net/$ | awk '/.*:.*:.*/'` ; do #echo "#ipportinode=$ipportinode" inode=`echo "$ipportinode" | cut -d"|" -f3` ; if [ "#$inode" = "#" ] ; then continue ; fi lspid=`ls -l /proc/*/fd/* 2>/dev/null | grep "socket:\[$inode\]" 2>/dev/null` ; pid=`echo "lspid=$lspid" | awk 'BEGIN /socket/'` ; if [ "#$pid" = "#" ] ; then continue ; fi exefile=`ls -l /proc/$pid/exe | awk 'BEGIN ">/->/'` #echo "$protocol|$pid|$ipportinode" echo "$protocol|$pid|$ipportinode|$exefile" | awk ' BEGIN function iphex2dec(ipport) < ret=sprintf("%d.%d.%d.%d: %d","0x"substr(ipport,1,2),"0x"substr(ipport,3,2), "0x"substr(ipport,5,2),"0x"substr(ipport,7,2),"0x"substr(ipport,10,4)) ; if( ret == "0.0.0.0:0" ) #compatibility others awk versions < ret= strtonum("0x"substr(ipport,1,2)) ; ret=ret "." strtonum("0x"substr(ipport,3,2)) ; ret=ret "." strtonum("0x"substr(ipport,5,2)) ; ret=ret "." strtonum("0x"substr(ipport,7,2)) ; ret=ret ":" strtonum("0x"substr(ipport,10)) ; >return ret ; > < print $1" pid:"$2" local="iphex2dec($3)" remote="iphex2dec($4)" inode:"$5" exe=" $6 ; >' ; #ls -l /proc/$pid/exe ; done ; done 
tcp pid:1454 local=1.0.0.127:5939 remote=0.0.0.0:0 inode:13955 exe=/opt/teamviewer/tv_bin/teamviewerd tcp pid:1468 local=1.1.0.127:53 remote=0.0.0.0:0 inode:12757 exe=/usr/sbin/dnsmasq tcp pid:1292 local=0.0.0.0:22 remote=0.0.0.0:0 inode:12599 exe=/usr/sbin/sshd tcp pid:4361 local=1.0.0.127:631 remote=0.0.0.0:0 inode:30576 exe=/usr/sbin/cupsd tcp pid:1375 local=1.0.0.127:5432 remote=0.0.0.0:0 inode:12650 exe=/usr/lib/postgresql/9.3/bin/postgres 

With ls you can know the process route.

The fuser command says that the process is: 2054

I’ve added IPv6 support and made a few fixes. Additionally on my system the octets of the IP address are reversed. Dependencies are only to posix shell, awk and cut.

My Version can be found on Github

#!/bin/sh # prints all open ports from /proc/net/* # # for pretty output (if available) start with # ./linux-get-programm-to-port.sh | column -t -s $'\t' #set -x ip4hex2dec () < local ip4_1octet="0x$" local ip4_2octet="$" ip4_2octet="0x$" local ip4_3octet="$" ip4_3octet="0x$" local ip4_4octet="$" ip4_4octet="0x$" local ip4_port="0x$" # if not used inverse #printf "%d.%d.%d.%d:%d" "$ip4_1octet" "$ip4_2octet" "$ip4_3octet" "$ip4_4octet" "$ip4_port" printf "%d.%d.%d.%d:%d" "$ip4_4octet" "$ip4_3octet" "$ip4_2octet" "$ip4_1octet" "$ip4_port" > # reoder bytes, byte4 is byte1 byte2 is byte3 . reorderByte() < if [ $-ne 8 ]; then echo "missuse of function reorderByte"; exit; fi local byte1="$" local byte2="$" byte2="$" local byte3="$" byte3="$" local byte4="$" echo "$byte4$byte3:$byte2$byte1" > # on normal intel platform the byte order of the ipv6 address in /proc/net/*6 has to be reordered. ip6hex2dec()< local ip_str="$" local ip6_port="0x$" local ipv6="$(reorderByte $)" local shiftmask="$" ipv6="$ipv6:$(reorderByte $)" shiftmask="$" ipv6="$ipv6:$(reorderByte $)" ipv6="$ipv6:$(reorderByte $)" ipv6=$(echo $ipv6 | awk '< gsub(/(:0|^0)/, ":"); sub(/(:0)+:/, "::");print>') printf "%s:%d" "$ipv6" "$ip6_port" > for protocol in tcp tcp6 udp udp6 raw raw6; do #echo "protocol $protocol" ; for ipportinode in `cat /proc/net/$protocol | awk '/.*:.*:.*/'` ; do #echo "#ipportinode=$ipportinode" inode=$ if [ "#$inode" = "#" ] ; then continue ; fi lspid=`ls -l /proc/*/fd/* 2>/dev/null | grep "socket:\[$inode\]" 2>/dev/null` ; pids=`echo "$lspid" | awk 'BEGIN /socket/ END>'` ; # removes duplicats for this pid #echo "#lspid:$lspid #pids:$pids" for pid in $pids; do if [ "#$pid" = "#" ] ; then continue ; fi exefile=`ls -l /proc/$pid/exe | awk 'BEGIN ">/->/'`; cmdline=`cat /proc/$pid/cmdline` local_adr_hex=$ remote_adr_hex=$ remote_adr_hex=$ if [ "#$" = "#6" ]; then local_adr=$(ip6hex2dec $local_adr_hex) remote_adr=$(ip6hex2dec $remote_adr_hex) else local_adr=$(ip4hex2dec $local_adr_hex) remote_adr=$(ip4hex2dec $remote_adr_hex) fi echo "$protocol pid:$pid \t$local_adr \t$remote_adr \tinode:$inode \t$exefile $cmdline" done done done 

Источник

Кто слушает порт в 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

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

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

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

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

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

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

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

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

Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:10843 0.0.0.0:* LISTEN 7023/node tcp 0 0 127.0.0.1:4942 0.0.0.0:* LISTEN 3413/java .

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

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

lrwxrwxrwx. 1 user user 0 Nov 10 20:31 /proc/3413/exe -> /opt/jdk1.8.0_60/bin/java

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

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

tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1607/apache2

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

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

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

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

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

lsof -i :$portNumber lsof -i tcp:$portNumber lsof -i udp:$portNumber

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

apache2 2123 root 3u IPv4 6472 0t0 TCP *:www (LISTEN) apache2 2124 www-data 3u IPv4 6472 0t0 TCP *:www (LISTEN) apache2 2125 www-data 3u IPv4 6472 0t0 TCP *:www (LISTEN) apache2 2126 www-data 3u IPv4 6472 0t0 TCP *:www (LISTEN)

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

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

www-data 2124 0.0 0.0 36927 4991 ? S 10:20 0:00 /usr/sbin/apache2 -k start

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

$ ps -eo pid,user,group,args,etime,lstart | grep '2727'
2727 www-data www-data /usr/sbin/apache2 -k start 14:27:33 Mon Nov 30 21:21:28 2015

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

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

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

Источник

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).

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.

Источник

Читайте также:  Настроить vnc сервер linux
Оцените статью
Adblock
detector