- 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
- How to check if port is in use on Linux or Unix
- How to check if port is in use in
- Option #1: lsof command
- Option #2: netstat command
- Linux netstat syntax
- FreeBSD/MacOS X netstat syntax
- OpenBSD netstat syntax
- Option #3: nmap command
- A note about Windows users
- Conclusion
- Determining what process is bound to a port
- 5 Answers 5
- How can I see what ports are open on my machine?
- 10 Answers 10
- nmap (install)
- Как проверить прослушивающие порты в Linux (используемые порты)
- Что такое порт прослушивания
- Проверьте порты прослушивания с помощью netstat
- Проверьте порты прослушивания с помощью ss
- Проверьте порты прослушивания с помощью lsof
- Выводы
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
Источник
How to check if port is in use on Linux or Unix
H ow do I determine if a port is in use under Linux or Unix-like system? How can I verify which ports are listening on Linux server? How do I check if port is in use on Linux operating system using the CLI?
It is important you verify which ports are listening on the server’s network interfaces. You need to pay attention to open ports to detect an intrusion. Apart from an intrusion, for troubleshooting purposes, it may be necessary to check if a port is already in use by a different application on your servers. For example, you may install Apache and Nginx server on the same system. So it is necessary to know if Apache or Nginx is using TCP port # 80/443. This quick tutorial provides steps to use the netstat, nmap and lsof command to check the ports in use and view the application that is utilizing the port.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | lsof, ss, and netstat on Linux |
Est. reading time | 3 minutes |
How to check if port is in use in
To check the listening ports and applications on Linux:
- Open a terminal application i.e. shell prompt.
- Run any one of the following command on Linux to see open ports:
sudo lsof -i -P -n | grep LISTEN
sudo netstat -tulpn | grep LISTEN
sudo ss -tulpn | grep LISTEN
sudo lsof -i:22 ## see a specific port such as 22 ##
sudo nmap -sTU -O IP-address-Here - For the latest version of Linux use the ss command. For example, ss -tulw
Let us see commands and its output in details.
Option #1: lsof command
The syntax is:
$ sudo lsof -i -P -n
$ sudo lsof -i -P -n | grep LISTEN
$ doas lsof -i -P -n | grep LISTEN ### [OpenBSD] ###
Sample outputs:
Fig.01: Check the listening ports and applications with lsof command
Option #2: netstat command
You can check the listening ports and applications with netstat as follows.
Linux netstat syntax
Run netstat command along with grep command to filter out port in LISTEN state:
$ netstat -tulpn | grep LISTEN
The netstat command deprecated for some time on Linux. Therefore, you need to use the ss command as follows:
sudo ss -tulw
sudo ss -tulwn
sudo ss -tulwn | grep LISTEN
Where, ss command options are as follows:
- 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 ➔
- -t : Show only TCP sockets on Linux
- -u : Display only UDP sockets on Linux
- -l : Show listening sockets. For example, TCP port 22 is opened by SSHD server.
- -p : List process name that opened sockets
- -n : Don’t resolve service names i.e. don’t use DNS
FreeBSD/MacOS X netstat syntax
$ netstat -anp tcp | grep LISTEN
$ netstat -anp udp | grep LISTEN
OpenBSD netstat syntax
$ netstat -na -f inet | grep LISTEN
$ netstat -nat | grep LISTEN
Option #3: nmap command
The syntax is:
$ sudo nmap -sT -O localhost
$ sudo nmap -sU -O 192.168.2.13 ##[ list open UDP ports ]##
$ sudo nmap -sT -O 192.168.2.13 ##[ list open TCP ports ]##
Sample outputs:
Fig.02: Determines which ports are listening for TCP connections using nmap
A note about Windows users
You can check port usage from Windows operating system using following command:
netstat -bano | more
netstat -bano | grep LISTENING
netstat -bano | findstr /R /C:»[LISTEING]»
Conclusion
This page explained command to determining if a port is in use on Linux or Unix-like server. For more information see the nmap command and lsof command page online here
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Determining what process is bound to a port
I know that using the command:
(or some variant of parameters with lsof) I can determine which process is bound to a particular port. This is useful say if I’m trying to start something that wants to bind to 8080 and some else is already using that port, but I don’t know what.
Is there an easy way to do this without using lsof? I spend time working on many systems and lsof is often not installed.
5 Answers 5
netstat -lnp will list the pid and process name next to each listening port. This will work under Linux, but not all others (like AIX.) Add -t if you want TCP only.
On AIX, netstat & rmsock can be used to determine process binding:
Another tool available on Linux is ss. From the ss man page on Fedora:
Example output below — the final column shows the process binding:
For Solaris you can use pfiles and then grep by sockname: or port: .
I was once faced with trying to determine what process was behind a particular port (this time it was 8000). I tried a variety of lsof and netstat, but then took a chance and tried hitting the port via a browser (i.e. http://hostname:8000/). Lo and behold, a splash screen greeted me, and it became obvious what the process was (for the record, it was Splunk).
One more thought: «ps -e -o pid,args» (YMMV) may sometimes show the port number in the arguments list. Grep is your friend!
Источник
How can I see what ports are open on my machine?
I would like to see what ports are open on my machine, e.g. what ports my machine is listening on. E.g. port 80 if I have installed a web server, and so on.
Is there any command for this?
10 Answers 10
I’ve always used this:
If the netstat command is not available, install it with:
nmap (install)
Nmap («Network Mapper») is a free and open source utility for network exploration or security auditing.
Use nmap 192.168.1.33 for internal PC or nmap external IP address .
More information man nmap .
Zenmap is the official GUI frontend.
Other good ways to find out what ports are listenting and what your firewall rules are:
sudo netstat -tulpn
sudo ufw status
To list open ports use the netstat command.
In the above example three services are bound to the loopback address.
IPv4 services bound to the loopback address «127.0.0.1» are only available on the local machine. The equivalent loopback address for IPv6 is «::1». The IPv4 address «0.0.0.0» means «any IP address», which would mean that other machines could potentially connect to any of the locally configured network interfaces on the specific port.
Another method is to use the lsof command:
For more details see man netstat or man lsof .
Источник
Как проверить прослушивающие порты в Linux (используемые порты)
При устранении неполадок сетевого подключения или проблем, связанных с конкретным приложением, в первую очередь следует проверить, какие порты фактически используются в вашей системе и какое приложение прослушивает конкретный порт.
В этой статье объясняется, как использовать команды netstat , ss и lsof чтобы узнать, какие службы прослушивают какие порты. Инструкции применимы для всех операционных систем Linux и Unix, таких как macOS.
Что такое порт прослушивания
Сетевой порт идентифицируется по его номеру, связанному IP-адресу и типу протокола связи, например TCP или UDP.
Порт прослушивания — это сетевой порт, на котором приложение или процесс прослушивает, выступая в качестве конечной точки связи.
Каждый порт прослушивания может быть открыт или закрыт (отфильтрован) с помощью брандмауэра. В общих чертах, открытый порт — это сетевой порт, который принимает входящие пакеты из удаленных мест.
У вас не может быть двух служб, слушающих один и тот же порт на одном IP-адресе.
Например, если вы используете веб-сервер Apache, который прослушивает порты 80 и 443 и вы пытаетесь установить Nginx , последний не запустится, потому что порты HTTP и HTTPS уже используются.
Проверьте порты прослушивания с помощью netstat
netstat — это инструмент командной строки, который может предоставить информацию о сетевых подключениях.
Чтобы вывести список всех прослушиваемых портов TCP или UDP, включая службы, использующие порты, и статус сокета, используйте следующую команду:
Параметры, используемые в этой команде, имеют следующее значение:
- -t — Показать TCP-порты.
- -u — Показать порты UDP.
- -n — Показывать числовые адреса вместо разрешающих узлов.
- -l — Показать только прослушивающие порты.
- -p — Показать PID и имя процесса слушателя. Эта информация отображается только в том случае, если вы запускаете команду от имени пользователя root или sudo .
Результат будет выглядеть примерно так:
Важными столбцами в нашем случае являются:
- Proto — протокол, используемый сокетом.
- Local Address — IP-адрес и номер порта, который прослушивает процесс.
- PID/Program name — PID и имя процесса.
Если вы хотите отфильтровать результаты, используйте команду grep . Например, чтобы узнать, какой процесс прослушивает TCP-порт 22, введите:
Выходные данные показывают, что на этой машине порт 22 используется сервером SSH:
Если вывод пуст, это означает, что порт ничего не прослушивает.
Вы также можете фильтровать список по критериям, например, PID, протоколу, состоянию и так далее.
netstat устарел и заменен ss и ip , но все же это одна из наиболее часто используемых команд для проверки сетевых подключений.
Проверьте порты прослушивания с помощью ss
ss — это новый netstat . В нем отсутствуют некоторые функции netstat , но он предоставляет больше состояний TCP и работает немного быстрее. Параметры команды в основном те же, поэтому переход с netstat на ss не представляет труда.
Чтобы получить список всех прослушивающих портов с помощью ss , введите:
Результат почти такой же, как у netstat :
Проверьте порты прослушивания с помощью lsof
lsof — это мощная утилита командной строки, которая предоставляет информацию о файлах, открытых процессами.
В Linux все является файлом. Вы можете думать о сокете как о файле, который записывает в сеть.
Чтобы получить список всех прослушивающих TCP-портов с типом lsof :
Используются следующие параметры:
- -n — Не преобразовывать номера портов в имена портов.
- -p — Не разрешать имена хостов, показывать числовые адреса.
- -iTCP -sTCP:LISTEN — Показать только сетевые файлы с состоянием TCP LISTEN.
Большинство имен выходных столбцов говорят сами за себя:
- COMMAND , PID , USER — имя, pid и пользователь, запускающий программу, связанную с портом.
- NAME — номер порта.
Чтобы узнать, какой процесс прослушивает определенный порт, например порт 3306 вы должны использовать:
Выходные данные показывают, что сервер MySQL использует порт 3306 :
Для получения дополнительной информации посетите страницу руководства lsof и прочтите обо всех других мощных возможностях этого инструмента.
Выводы
Мы показали вам несколько команд, которые вы можете использовать, чтобы проверить, какие порты используются в вашей системе, и как узнать, какой процесс прослушивает определенный порт.
Если у вас есть вопросы или замечания, пожалуйста, оставьте комментарий ниже.
Источник