- 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
- How to Check Service Running on Specific Port on Linux
- 1) Using Netstat Command
- Usage
- 2) Using fuser Command
- 3) Using lsof Command
- 4) Using Whatportis Tool
- Usage of Whatportis
- More Articles You May Like
- 1 thought on “How to Check Service Running on Specific Port on Linux”. add one
- Как посмотреть открытые порты в Linux
- Как посмотреть открытые порты linux
- 1. netstat
- 3. lsof
- 4. Nmap
- 5. Zenmap
- Выводы
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
Источник
How to Check Service Running on Specific Port on Linux
Occasionally, we may need to check out the default port number of specific services/protocols or services listening on certain ports on Linux. A number of command line tools are available to help you search port names and numbers in your Linux System.
1) Using Netstat Command
Nestat command is a tool used for checking active network connections, interface statistics as well as the routing table. It’s available in all Linux distributions. However, for minimal installations, you can install it by running
For RedHat and CentOS
For Fedora 22 and later
Usage
To display detailed information of TCP and UDP endpoints run
Output
- -p flag Gives the process ID and the process name.
- -n flag displays numerical addresses
- -l flag displays listening sockets
- -t flag shows TCP connections
- -u flag shows UDP connections
To find a service listening to a specific port run
Output
Similarly, to find which port a service is listening on run
Output
2) Using fuser Command
fuser command is used for displaying Process IDs of services running on specific ports.
It’s not installed by default in most systems. To install it run
For RedHat and CentOS
ForFedoraa 22 and later
For Debian and Ubuntu
For example, to find PIDs running on port 80 run,
Output
To search for process name using process PID run
Output
3) Using lsof Command
lsof command can be used to examine active TCP and UDP endpoints. To install the command line tool
For RedHat and CentOS
ForFedoraa 22 and later
For Debian and Ubuntu
To display active TCP and UDP endpoints with lsof run ,
Output
To display processes /services listening on a particular port, type the command below as you specify the port
4) Using Whatportis Tool
Whatportis is a command line tool that allows you to search port names and numbers of services running in your system. The tool fetches the list of official TCP/UDP ports from iana website. As a result, a private script is created to regularly fetch the website and update the ports.json fileTo use the command line tool, we must first of all, install it in our system.
First, we need to install python-pip
For Ubuntu 16 and later & Debian Systems
For RHEL & CentOS Systems
Install EPEL repository
Next, Install python setup tools
Finally, install whatportis using pip
Usage of Whatportis
To search for a port associated with a service name run
Conversely, you can search for the service associated with the port number
You can also search a pattern without knowing the exact name by running
You can also display results as JSON output
That’s all we had for today. As always we cherish your thoughts and your feedback is always welcome. Feel free to reach us via the comment section below. Thank you for your time and stay tuned for more informative tutorials.
More Articles You May Like
1 thought on “How to Check Service Running on Specific Port on Linux”. add one
Awesome post and informative.
Thanks
If you don’t mind I can share some addition info with this post.
if you want to find the port list of oracle application and database in linux system then you can follow below link.
https://oracleappsdbaworkshop.blogspot.com/2019/01/how-to-find-portpoollst-or-how-to-find.html
I think this post and my referred link will help many people who are working with Linux and oracle EBS.
Источник
Как посмотреть открытые порты в Linux
Сетевые порты — это механизм, с помощью которого операционная система определяет какой именно программе необходимо передать сетевой пакет. Здесь можно привести пример с домом. Например, почтальону необходимо доставить посылку. Он доставляет посылку к дому, это IP адрес компьютера. А дальше в самом доме уже должны разобраться в какую квартиру направить эту посылку. Номер квартиры — это уже порт.
Если порт открыт это означает, что какая либо программа, обычно сервис, использует его для связи с другой программой через интернет или в локальной системе. Чтобы посмотреть какие порты открыты в вашей системе Linux можно использовать множество различных утилит. В этой статье мы рассмотрим самые популярные способы посмотреть открытые порты Linux.
Как посмотреть открытые порты linux
1. netstat
Утилита netstat позволяет увидеть открытые в системе порты, а также открытые на данный момент сетевые соединения. Для отображения максимально подробной информации надо использовать опции:
- -l или —listening — посмотреть только прослушиваемые порты;
- -p или —program — показать имя программы и ее PID;
- -t или —tcp — показать tcp порты;
- -u или —udp показать udp порты;
- -n или —numeric показывать ip адреса в числовом виде.
Открытые порты Linux, которые ожидают соединений имеют тип LISTEN, а перед портом отображается IP адрес на котором сервис ожидает подключений. Это может быть определенный IP адрес или */0.0.0.0 что означают любой доступный адрес:
sudo netstat -tulpn
Утилита ss — это современная альтернатива для команды netstat. В отличие от netstat, которая берет информацию из каталога /proc, утилита ss напрямую связывается со специальной подсистемой ядра Linux, поэтому работает быстрее и её данные более точные, если вы хотите выполнить просмотр открытых портов это не имеет большого значения. Опции у неё такие же:
Можно вывести только процессы, работающие на 80-том порту:
sudo ss -tulpn | grep :80
3. lsof
Утилита lsof позволяет посмотреть все открытые в системе соединения, в том числе и сетевые, для этого нужно использовать опцию -i, а чтобы отображались именно порты, а не названия сетевых служб следует использовать опцию -P:
Ещё один пример, смотрим какие процессы работают с портом 80:
sudo lsof -i -P | grep :80
4. Nmap
Программа Nmap — мощный сетевой сканер, разработанный для сканирования и тестирования на проникновение удаленных узлов, но ничего не мешает направить его на локальный компьютер. Утилита позволяет не только посмотреть открытые порты, но и примерно определить какие сервисы их слушают и какие уязвимости у них есть. Программу надо установить:
sudo apt install nmap
Затем можно использовать:
Для простого сканирования можно запускать утилиту без опций. Детальнее о её опциях можно узнать в статье про сканирование сети в Nmap. Эта утилита ещё будет полезна если вы хотите посмотреть какие порты на компьютере доступны из интернета.
Если это публичный сервер, то результат скорее всего не будет отличатся от локального сканирования, но на домашнем компьютере все немного по другому. Первый вариант — используется роутер и в сеть будут видны только порты роутера, еще одним порогом защиты может стать NAT-сервер провайдера. Технология NAT позволяет нескольким пользователям использовать один внешний IP адрес. И так для просмотра открытых внешних портов сначала узнаем внешний ip адрес, для надежности воспользуемся онлайн сервисом:
wget -O — -q eth0.me
Дальше запускаем сканирование:
В результате мы видим, что открыт порт 80 веб-сервера и 22 — порт службы ssh, я их не открывал, эти порты открыты роутером, 80 — для веб-интерфейса, а 22 для может использоваться для обновления прошивки. А еще можно вообще не получить результатов, это будет означать что все порты закрыты, или на сервере установлена система защиты от вторжений IDS. Такая проверка портов может оказаться полезной для того, чтобы понять находится ли ваш компьютер в безопасности и нет ли там лишних открытых портов, доступных всем.
5. Zenmap
Программа Zenmap — это графический интерфейс для nmap. Она не делает ничего нового кроме того, что может делать nmap, просто предоставляет ко всему этому удобный интерфейс. Для её установки выполните:
sudo apt install zenmap
Запустить программу можно из главного меню или командой:
Затем введите адрес localhost в поле Цель и нажмите кнопку Сканирование:
После завершения сканирования утилита вывела список открытых портов Linux.
Выводы
В этой статье мы рассмотрели инструменты, которые вы можете использовать для того чтобы узнать узнать открытые порты linux. Инструментов не так много как для просмотра информации об оперативной памяти или процессоре, но их вполне хватает. А какими программами пользуетесь вы? Напишите в комментариях!
Источник