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 

Источник

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

Команда netstat, входящая в стандартный набор сетевых инструментов UNIX, отображает различную network–related информацию, такую как сетевые подключения, статистику интерфейсов, таблицы маршрутизации, masquerade, multicast, и т.п.

В этой статье рассмотрим десять практических примеров использования команды netstat в Linux.

1. Список всех портов (как прослушиваемых, так и нет)

Перечислить все порты: netstat -a

# netstat -a | more Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 localhost:domain *:* LISTEN udp6 0 0 fe80::20c:29ff:fe68:ntp [::]:* Active UNIX domain sockets (servers and established) Proto RefCnt Flags Type State I-Node Path unix 2 [ ACC ] STREAM LISTENING 20492 /var/run/mysqld/mysqld.sock unix 2 [ ACC ] STREAM LISTENING 23323 /var/run/php5-fpm.sock

Перечислить все TCP порты: netstat -at

# netstat -at Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 localhost:domain *:* LISTEN tcp 0 0 *:ssh *:* LISTEN tcp 0 0 localhost:ipp *:* LISTEN tcp 0 0 *:http *:* LISTEN

Перечислить все UDP порты: netstat -au

# netstat -au Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State udp 0 0 localhost:domain *:* udp 0 0 *:bootpc *:* udp6 0 0 fe80::20c:29ff:fe68:ntp [::]:*

2. Список сокетов, находящихся в состоянии LISTEN

Перечислить все прослушиваемые порты: netstat -l

# netstat -l Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 localhost:domain *:* LISTEN tcp6 0 0 [::]:ssh [::]:* LISTEN udp 0 0 192.168.128.134:ntp *:*

Перечислить прослушиваемые TCP порты: netstat -lt

# netstat -lt Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 localhost:domain *:* LISTEN tcp 0 0 localhost:ipp *:* LISTEN tcp6 0 0 [::]:ssh [::]:* LISTEN

Перечислить прослушиваемые UDP порты: netstat -lu

# netstat -lu Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State udp 0 0 *:bootpc *:* udp6 0 0 [::]:ntp [::]:*

Перечислить прослушиваемые UNIX сокеты: netstat -lx

# netstat -lx Active UNIX domain sockets (only servers) Proto RefCnt Flags Type State I-Node Path unix 2 [ ACC ] STREAM LISTENING 3141 /var/run/fail2ban/fail2ban.sock unix 2 [ ACC ] STREAM LISTENING 20492 /var/run/mysqld/mysqld.sock unix 2 [ ACC ] STREAM LISTENING 23323 /var/run/php5-fpm.sock

3. Просмотр статистики для каждого протокола

Показать статистику всех портов: netstat -s

# netstat -s Ip: 11150 total packets received 1 with invalid addresses 0 forwarded 0 incoming packets discarded 11149 incoming packets delivered 11635 requests sent out Icmp: 13791 ICMP messages received 12 input ICMP message failed. Tcp: 15020 active connections openings 97955 passive connection openings 135 failed connection attempts Udp: 2841 packets received 180 packets to unknown port received. .

Показать статистику только TCP портов: netstat -st

Показать статистику только UDP портов: netstat -su

4. Отображение PID и имени процесса в выводе netstat

Опция netstat -p добавит «PID/Program Name» в вывод netstat, и может быть совмещена с любым другим набором опций. Это очень полезно при отладке, для определения того, какая программа работает на определённом порту.

# netstat -pt Active Internet connections (w/o servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 org-ru-putty.vm.udf:www 52-106.plus.kerch:55723 ESTABLISHED 9486/nginx: worker tcp 0 0 org-ru-putty.vm.udf:www 52-106.plus.kerch:55757 ESTABLISHED 9486/nginx: worker

5. Разрешение имён в выводе netstat

Когда вам не нужно резолвить имя хоста, имя порта, имя пользователя, используйте опцию netstat -n для вывода значений в цифровом формате. Команда покажет IP-адрес вместо хоста, номер порта вместо имени порта, UID вместо имени пользователя.

Это также ускорит вывод, так как netstat не станет выполнять ненужный поиск.

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

# netsat -a --numeric-ports # netsat -a --numeric-hosts # netsat -a --numeric-users

6. Вывод информации netstat непрерывно

Опция netstat -c будет выводить информацию непрерывно, в стиле top, обновляя экран каждые несколько секунд.

# netstat -c Active Internet connections (w/o servers) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 org-ru-putty.vm.udf:www 182.131.74.202:59933 FIN_WAIT2 tcp 0 0 org-ru-putty.vm.udf:www 182.131.74.202:63761 FIN_WAIT2 tcp 0 0 org-ru-putty.vm.udf:www 92-181-66-102-irk.:4585 ESTABLISHED ^C

7. Неподдерживаемые системой семейства адресов

Опция netstat —verbose покажет подробный вывод, а в самом конце отобразит неподдерживаемые Address Family.

netstat: no support for `AF IPX' on this system. netstat: no support for `AF AX25' on this system. netstat: no support for `AF X25' on this system. netstat: no support for `AF NETROM' on this system.

8. Маршрутизация ядра

Показать таблицу маршрутизации ядра: netstat -r

# netstat -r Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface default 192.168.128.2 0.0.0.0 UG 0 0 0 eth0 192.168.128.0 * 255.255.255.0 U 0 0 0 eth0

Примечание: Используйте netstat -rn для просмотра маршрута в цифровом формате без разрешения имён узлов.

9. Соответствие портов и процессов

Узнать, какой порт занимает определённая программа:

# netstat -ap | grep ssh (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) tcp 0 0 *:ssh *:* LISTEN - tcp6 0 0 [::]:ssh [::]:* LISTEN -

Выяснить, каким процессом используется определённый порт:

10. Сетевые интерфейсы

Показать список сетевых интерфейсов: netstat -i

# netstat -i Kernel Interface table Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg eth0 1500 0 1911037 0 0 0 1382056 0 0 0 BMRU lo 16436 0 0 0 0 0 0 0 0 0 LRU

Показать расширенную информацию об интерфейсах (аналогично ifconfig): netstat -ie

# netstat -ie Kernel Interface table eth0 Link encap:Ethernet HWaddr 00:0c:29:68:4c:a4 inet addr:192.168.128.134 Bcast:192.168.128.255 Mask:255.255.255.0 inet6 addr: fe80::20c:29ff:fe68:4ca4/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:24278 errors:0 dropped:0 overruns:0 frame:0 TX packets:11275 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:33203025 (33.2 MB) TX bytes:665822 (665.8 KB) Interrupt:19 Base address:0x2000

11. netstat -lnptux

  • -l все открытые порты (LISTEN)
  • -t по протоколу TCP
  • -u по протоколу UDP
  • -x по протоколу UNIX Socket
  • -n без резолва IP/имён
  • -p но с названиями процессов и PID-ами

Примечание: Не все процессы могут быть идентифицированы последним ключом, чужие процессы показаны не будут. Вы должны иметь права root чтобы увидеть всё.

# netstat -lnptux Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 9614/nginx tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 601/sshd udp 0 0 8.8.4.4:123 0.0.0.0:* 574/ntpd udp 0 0 127.0.0.1:123 0.0.0.0:* 574/ntpd udp 0 0 0.0.0.0:123 0.0.0.0:* 574/ntpd Active UNIX domain sockets (only servers) Proto RefCnt Flags Type State I-Node PID/Program name Path unix 2 [ ACC ] STREAM LISTENING 4233 826/python /var/run/fail2ban/fail2ban.sock unix 2 [ ACC ] STREAM LISTENING 8122 2561/mysqld /var/run/mysqld/mysqld.sock unix 2 [ ACC ] STREAM LISTENING 160413 7301/php-fpm.conf /var/run/php5-fpm.sock

Источник

Читайте также:  Konica minolta bizhub 163 драйвер linux
Оцените статью
Adblock
detector