Ports and services linux

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.

1 thought on “How to Check Service Running on Specific Port on Linux”. add one

Awesome post and informative.
Thanks

Читайте также:  Менеджер архивов linux mint кодировка

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.

Источник

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:

  1. Open a terminal application i.e. shell prompt.
  2. 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
  3. 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

Источник

Как узнать, какой номер порта используется процессом в Linux?

Как администратор Linux, вы должны знать, является ли соответствующая служба обязательной / прослушивающей с правильным портом или нет.

Это поможет вам легко устранить проблему, когда вы столкнулись с проблемами, связанными с портами.

Порт – это логическое соединение, которое идентифицирует конкретный процесс в Linux.

Доступны два вида порта: физическое и программное обеспечение.

Поскольку операционная система Linux является программным обеспечением, мы собираемся обсудить порт программного обеспечения.

Программный порт всегда связан с IP-адресом хоста и соответствующим типом протокола для связи. Порт используется для распознования приложения.

Большинство служб, связанных с сетью, должны открыть сокет для прослушивания входящих сетевых запросов.

Socket уникален для каждого сервиса.

Сокет – это комбинация IP-адреса, программного порта и протокола.

Область номеров портов доступна для протокола TCP и UDP.

Протокол управления передачей (TCP) и протокол пользовательских дейтаграмм (UDP) используют номера портов для связи.

Это значение от 0 до 65535.

Ниже приведены категории присвоений портов.

  • 0-1023: Хорошо известные порты или системные порты
  • 1024-49151: Зарегистрированные порты для приложений
  • 49152-65535: Динамические порты или частные порты

Вы можете проверить детали зарезервированных портов в файле /etc/services в Linux.

Это может быть достигнуто с использованием шести методов.

  • ss: ss используется для вывода статистики сокетов.
  • netstat: netstat отображает список открытых сокетов.
  • lsof: lsof – список открытых файлов.
  • fuser: идентификаторы процессов в списке терминов всех процессов, которые открывают один или несколько файлов
  • nmap: nmap – Инструмент сетевого исследования и сканер безопасности / портов
  • systemctl: systemctl – Управление системой systemd и менеджером сервисов

Метод-1: Использование команды ss

ss используется для вывода статистики сокетов.

Он позволяет отображать информацию, аналогичную netstat.

Он может отображать больше информации о TCP и его состоянии, чем другие инструменты.

Он может отображать статистику для всех типов сокетов, таких как PACKET, TCP, UDP, DCCP, RAW, домен Unix и т. д.

В качестве альтернативы вы также можете проверить это с помощью номера порта.

Способ-2: Использование команды netstat

netstat – вывод сетевых подключений, таблиц маршрутизации, статистики интерфейсов, соединений маскарада и многоадресной рассылки.

По умолчанию netstat отображает список открытых сокетов.

Если вы не укажете каких-либо семейств адресов, будут выведены активные сокеты всех сконфигурированных семейств адресов.

Эта программа устарела. Замена для netstat – ss.

В качестве альтернативы вы также можете проверить это с помощью номера порта.

Метод-3: использование команды lsof

lsof – список открытых файлов.

Команда lsof Linux выводит информацию о файлах, открытых для процессов, запущенных в системе.

В качестве альтернативы вы также можете проверить это с помощью номера порта.

Метод-4: Использование команды fuser

Утилита fuser должна записывать на стандартный вывод идентификаторы процессов, запущенных в локальной системе, которые открывают один или несколько именованных файлов.

Метод-5: Использование команды nmap

Nmap («Network Mapper») – это инструмент с открытым исходным кодом для проверки сети и проверки безопасности.

Он был разработан для быстрого сканирования больших сетей, хотя он отлично работает с одиночными хостами.

Nmap использует необработанные IP-пакеты в новых способах определения того, какие хосты доступны в сети, какие службы (имя и версия приложения) эти хосты предлагают, какие операционные системы (и версии ОС) они запускают, какие типы фильтров пакетов / брандмауэры используются, и десятки других характеристик

Метод-6: Использование команды systemctl

systemctl – Управление системой systemd и менеджером сервисов.

Это замена старого системного управления SysV, и большинство современных операционных систем Linux были адаптированы под systemd.

Вышеприведенный пример будет показывать фактический порт прослушивания службы SSH при запуске службы SSHD в последнее время.

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

Источник

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:

  1. netstat command or ss command – a command-line tool that displays network connections, routing tables, and a number of network interface statistics.
  2. fuser command – a command line tool to identify processes using files or sockets.
  3. 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.
  4. /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

Источник

Читайте также:  Linux команда переместить файлы
Оцените статью