Linux listing open ports

Как посмотреть открытые порты в 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 что означают любой доступный адрес:

2. ss

Утилита ss — это современная альтернатива для команды netstat. В отличие от netstat, которая берет информацию из каталога /proc, утилита ss напрямую связывается со специальной подсистемой ядра Linux, поэтому работает быстрее и её данные более точные, если вы хотите выполнить просмотр открытых портов это не имеет большого значения. Опции у неё такие же:

Можно вывести только процессы, работающие на 80-том порту:

3. lsof

Утилита lsof позволяет посмотреть все открытые в системе соединения, в том числе и сетевые, для этого нужно использовать опцию -i, а чтобы отображались именно порты, а не названия сетевых служб следует использовать опцию -P:

Ещё один пример, смотрим какие процессы работают с портом 80:

4. Nmap

Программа Nmap — мощный сетевой сканер, разработанный для сканирования и тестирования на проникновение удаленных узлов, но ничего не мешает направить его на локальный компьютер. Утилита позволяет не только посмотреть открытые порты, но и примерно определить какие сервисы их слушают и какие уязвимости у них есть. Программу надо установить:

Читайте также:  Listing network interfaces linux

Для простого сканирования можно запускать утилиту без опций. Детальнее о её опциях можно узнать в статье про сканирование сети в Nmap. Эта утилита ещё будет полезна если вы хотите посмотреть какие порты на компьютере доступны из интернета.

Если это публичный сервер, то результат скорее всего не будет отличатся от локального сканирования, но на домашнем компьютере все немного по другому. Первый вариант — используется роутер и в сеть будут видны только порты роутера, еще одним порогом защиты может стать NAT-сервер провайдера. Технология NAT позволяет нескольким пользователям использовать один внешний IP адрес. И так для просмотра открытых внешних портов сначала узнаем внешний ip адрес, для надежности воспользуемся онлайн сервисом:

Дальше запускаем сканирование:

В результате мы видим, что открыт порт 80 веб-сервера и 22 — порт службы ssh, я их не открывал, эти порты открыты роутером, 80 — для веб-интерфейса, а 22 для может использоваться для обновления прошивки. А еще можно вообще не получить результатов, это будет означать что все порты закрыты, или на сервере установлена система защиты от вторжений IDS. Такая проверка портов может оказаться полезной для того, чтобы понять находится ли ваш компьютер в безопасности и нет ли там лишних открытых портов, доступных всем.

5. Zenmap

Программа Zenmap — это графический интерфейс для nmap. Она не делает ничего нового кроме того, что может делать nmap, просто предоставляет ко всему этому удобный интерфейс. Для её установки выполните:

Запустить программу можно из главного меню или командой:

Затем введите адрес localhost в поле Цель и нажмите кнопку Сканирование:

После завершения сканирования утилита вывела список открытых портов Linux.

Выводы

В этой статье мы рассмотрели инструменты, которые вы можете использовать для того чтобы узнать узнать открытые порты linux. Инструментов не так много как для просмотра информации об оперативной памяти или процессоре, но их вполне хватает. А какими программами пользуетесь вы? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to List Open Ports on Linux?

In networking, a port is an interesting feature. It’s a way for network traffic to identify the destination app or service. Each process/service gets its unique port. A port will always be associated with the IP address of the host along with the protocol.

This is a favorite metaphor of mine to describe what a port is. Imagine a ship loaded with cargo, which will travel to a distant land. What information is needed to reach the destination properly? For the sake of simplicity, let’s say it needs the country (the IP address) and the port the ship will dock.

In this guide, check out how to list open ports on Linux.

Ports on Linux

Ports act as an endpoint of communication. It’s a 16-bit number (0 to 65535 in decimal). While the range is large, for ease of use, ports are categorized into three categories. Each category is labeled as the range of port value:

  • 0 to 1023: These are the “Well-known” ports, also known as the “System” ports, which are reserved for system processes that offer a wide variety of network services. To bind with a “Well-known” port, a process must have superuser privilege.
  • 1024 to 49151: These are the “Registered” ports, also known as the “User” ports, that are designated by IANA for specific services. Upon request, a process may have access to them. In the case of most systems, it doesn’t require any superuser privilege to use these ports.
  • 49152 to 65535: These are the “Dynamic” ports, also known as the “Private” ports. These ports can’t be registered with IANA. These ports are open to using for private or customized services and may also be automatically allocated as ephemeral ports (short-lived ports used by IP).
Читайте также:  How to install with terminal linux

In Linux, there are multiple ways of checking the open ports. By default, any port will remain closed unless an app is using it. If a port is open, then it must be assigned to a service/process.

List Open Ports

It’s easier to identify which ports are in use rather than which ports are open. That’s why the following section will feature methods to list all the ports that are currently in use. In Linux, there are multiple tools available for the task. Most of them come built-in in any Linux distro.

Learning which ports are currently open can be useful in various scenarios. It’s possible to configure a dedicated port for a certain application. An open port may also be a strong indication of intrusion in the network.

The following methods are demonstrated on Ubuntu 20.04.1 LTS.

List protocols and open ports from /etc/services

The /etc/services file contains information about the currently running services. It’s a big file, so ready to get overwhelmed.

List open ports using netstat

The netstat tool is a utility for displaying network connections for TCP, routing tables, and various network interfaces. It also offers network protocol statistics. By using netstat, we can list all the open ports of the system.

Run the following netstat command:

Let’s have a quick breakdown of all the flags we used in this command.

  • a: Tells netstat to show all sockets
  • t: Tells netstat to list TCP ports
  • u: Tells netstat to list UDP ports

Here’s another variation of the netstat command:

There are two new flags used in the command. What do they mean?

  • l: Tells netstat to print only the listening sockets
  • n: Tells netstat to show the port number

To display the PID of the process that’s using a port, use the “-p” flag:

Читайте также:  Linux dns по умолчанию

List open ports using ss

The ss tool is a utility for investigating socket. Its usage is similar to netstat.

To list the open ports, run the following ss command:

The flags are similar to netstat. The functions they describe are also quite similar.

  • l: Tells ss to display listening sockets
  • n: Tells ss not to try to resolve service names
  • t: Tells ss to display TCP sockets
  • u: Tells ss to display UDP sockets

List open ports using lsof

The lsof command is to list open files. However, it can also be used for displaying the open ports.

Run the following lsof command:

To get the open ports of a specific protocol (TCP, UDP, etc.) then define it after the “-i” flag, use:

List open ports using nmap

The nmap tool is a powerful one for network exploration and security/port scanning. It can report all the open ports in the system.

To list the open TCP ports, run the following nmap command. Here, the IP address is of the host computer:

Here, there are two portions of the command argument.

  • -sT: This section tells nmap to scan for TCP ports.
  • -p- : This tells nmap to scan for all 65535 ports. If not used, then nmap will scan only 1000 ports by default.

If you need to list the open UDP ports, then run the following nmap command:

To get both the open TCP and UDP ports, use the following command:

List open ports using netcat

The netcat tool is a command line utility for reading and writing data across network connections over the TCP and UDP protocols. This tool can also be used for listing open ports. It can perform tests on a specific port or a range of ports.

The following netcat command will scan the port from 1 to 1000. The netcat command will perform the scan on TCP protocol by default:

It can also be extended to the entire list of possible ports:

Let’s have a quick breakdown of the flags.

  • z: Tells netcat to scan only for open ports without sending any data
  • v: Tells netcat to run in verbose mode

To get only the open ports from this list, filter the output with grep for the term “succeeded”.

If you want to perform the scan on UDP protocol, then add the “-u” flag.

Final Thoughts

As demonstrated, there are tons of ways to scan for open ports on Linux. I suggest trying out all the methods before you decide which one to master. If you’re using a certain tool like netcat or nmap regularly, then mastering the associated methods will be the most beneficial.

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.

Источник

Оцените статью
Adblock
detector