- How to find ports opened by process ID in Linux?
- -p (Linux):
- 3 Ways to Find Out Which Process Listening on a Particular Port
- 1. Using netstat Command
- 2. Using lsof Command
- 3. Using fuser Command
- How to find out which Port number a process is using
- 3 Answers 3
- Determine the process pid listening on a certain port
- 8 Answers 8
- Какой процесс слушает порт в 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
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).
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).
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=
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.
How to find out which Port number a process is using
I want to be able to find out which port number a process is and filtering the results using a keyword. For example, I may want to quickly find out which port numbers are being used by «node» js apps. This did not work:
netstat tulnap | grep "node"
By the way, i notice that on osx the command doesnt have a hyphen. Here are the results i got, not useful: Address Type Recv-Q Send-Q Inode Conn Refs Nextref Addr
3 Answers 3
This is how I found a solution:
» lsof -i -P | grep node node 14489 me 12u IPv4 0x. 0t0 TCP *:4000 (LISTEN)
Also if i knew the port and I was looking for the process name I would:
» lsof -i :4000 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME node 14489 me 12u IPv4 0x. 0t0 TCP *:terabase (LISTEN)
Active Internet connections (w/o servers)
Active Internet connections (only servers)
What you’re doing may also never work since GREP is never guaranteed to deliver either no, one, or more than 1 results.
But, in context of your specific case, any process IS actually unique, and has a unique number. So, you must do your search first to find a process number.
Doing a simple grep will still give you either none, one, or more than one process number. But you’ll need to find an additional filter, so that you end up with 1 process number.
If you have 1 process number, you can check port(s) being used by that process.
What makes you think «node» is reported in PS ? It may also not be.
Determine the process pid listening on a certain port
As the title says, I’m running multiple game servers, and every of them has the same name but different PID and the port number. I would like to match the PID of the server which is listening on certain port, and then I would like to kill this process. I need that in order to complete my bash script. Is that even possible? Because it didn’t find yet any solutions on the web.
8 Answers 8
Short version which you can pass to kill command:
This also includes processes that are connected on that port. lsof -i4TCP:80 -sTCP:LISTEN -t is probably what you want, instead.
Exactly what I was looking for. I wanted to kill a process by searching for the port it is running at.
@Nevir what do you mean by » also includes processes that are connected on that port»? Can you please explain?
The -p flag of netstat gives you PID of the process:
*use sudo if showing — instead of PID
Edit: The command that is needed to get PIDs of socket users in FreeBSD is sockstat . As we worked out during the discussion with @Cyclone, the line that does the job is:
sockstat -4 -l | grep :80 | awk '' | head -1
netstat: 80: unknown or uninstrumented protocol used the 80 (nginx) port for testing purpoes. Not worked.
netstat -p -l | grep $PORT and lsof -i :$PORT solutions are good but I prefer fuser $PORT/tcp extension syntax to POSIX (which work for coreutils ) as with pipe:
it prints pure pid so you can drop sed magic out.
One thing that makes fuser my lover tools is ability to send signal to that process directly (this syntax is also extension to POSIX):
$ fuser -k $port/tcp # with SIGKILL $ fuser -k -15 $port/tcp # with SIGTERM $ fuser -k -TERM $port/tcp # with SIGTERM
Какой процесс слушает порт в Linux?
17.05.2023
itpro
Linux
Комментариев пока нет
В этой статье мы рассмотрим, как найти процесс, который слушает определенный порт в Linux.
Можно получить информацию о процесс, который слушает определенный порт командой:
В этом примере видно, что порт 8000 занят процессом python3.
Можно вывести список всех запущенных процессов Linux, который используют любые TCP/UDP порты:
$ sudo netstat -lntup| grep LISTEN
Мы используем следующие ключи:
- -l – показать тольо прослушиваемые порты
- -n – показать IP адреса и номера портов в числовом виде и не пытаться их резолвить (соответствие номеров портов и название служб содержится в файле /etc/services)
- -t – показать открытые TCP порты
- -u – показать UDP порты
- -p – показать название процесс, который прослушивает порт
Мы нашли PID процесса ( 72005 ), который использует порт и теперь можно вывести информацию о том, как он запущен:
В этом примере видно, что процесс запущен вручную пользователем root с помощью команды python3 -m http.server (используется для запуска простого HTTP сервера на python для публикации текущего каталога).
Чтобы быстро завершить процесс, который слушает нужный вам порт и освободить его, выполните:
Проверьте, что порт теперь свободен:
Предыдущая статья Следующая статья
Установка и настройка прокси сервера Squid в Linux
Мониторинг срока регистрации (освобождения) домена в Zabbix
Настройка Wi-Fi точки доступа на Linux
Управление конфигурацией Windows через Ansible