Linux check listen 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 — мощный сетевой сканер, разработанный для сканирования и тестирования на проникновение удаленных узлов, но ничего не мешает направить его на локальный компьютер. Утилита позволяет не только посмотреть открытые порты, но и примерно определить какие сервисы их слушают и какие уязвимости у них есть. Программу надо установить:

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

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

Читайте также:  Bind linux to ldap

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

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

5. Zenmap

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

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

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

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

Выводы

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

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

Источник

4 Ways to Find Out What Ports Are Listening in Linux

The state of a port is either open, filtered, closed, or unfiltered. A port is said to be open if an application on the target machine is listening for connections/packets on that port.

In this article, we will explain four ways to check open ports and also will show you how to find which application is listening on what port in Linux.

1. Using Netstat Command

Netstat is a widely used tool for querying information about the Linux networking subsystem. You can use it to print all open ports like this:

The flag -l tells netstat to print all listening sockets, -t shows all TCP connections, -u displays all UDP connections and -p enables printing of application/program name listening on the port.

Check Open Ports Using Netstat Command

To print numeric values rather than service names, add the -n flag.

Show Numeric Values

You can also use grep command to find out which application is listening on a particular port, for example.

$ sudo netstat -lntup | grep "nginx"

Find Port of Running Application

Alternatively, you can specify the port and find the application bound to, as shown.

$ sudo netstat -lntup | grep ":80"

Find Application Using a Port Number

2. Using ss Command

ss command is another useful tool for displaying information about sockets. It’s output looks similar to that of netstat. The following command will show all listening ports for TCP and UDP connections in numeric value.

Find Open Ports Using ss Command

3. Using Nmap Command

Nmap is a powerful and popular network exploration tool and port scanner. To install nmap on your system, use your default package manager as shown.

$ sudo apt install nmap [On Debian/Ubuntu] $ sudo yum install nmap [On CentOS/RHEL] $ sudo dnf install nmap [On Fedora 22+]

To scan all open/listening ports in your Linux system, run the following command (which should take a long time to complete).

$ sudo nmap -n -PN -sT -sU -p- localhost

4. Using lsof Command

The final tool we will cover for querying open ports is lsof command, which is used to list open files in Linux. Since everything is a file in Unix/Linux, an open file may be a stream or a network file.

Читайте также:  Notebook with linux installed

To list all Internet and network files, use the -i option. Note that this command shows a mix of service names and numeric ports.

List Open Network Files Using lsof Command

To find which application is listening on a particular port, run lsof in this form.

Find Application Using Port

That’s all! In this article, we have explained four ways to check open ports in Linux. We also showed how to check which processes are bound upon particular ports. You can share your thoughts or ask any questions via the feedback form below.

Источник

How to Check (Scan) for Open Ports in Linux

In this tutorial, we will discuss many methods for determining which ports on your Linux system are available to the outside world.

How to Check (Scan) for Open Ports in Linux

Introduction

One of the first things to check when troubleshooting network connectivity issues or establishing a firewall is whether ports are truly open on your machine.

In this tutorial, we will discuss many methods for determining which ports on your Linux system are available to the outside world.

What is Open Port?

A program that listens on a network port is known as a listening port. You may retrieve a list of your system’s listening ports by using tools like ss , netstat , or lsof to query the network stack. Using a firewall, each listening port can be opened or blocked (filtered).

A network port that admits incoming packets from faraway destinations is known as an open port.

For instance, if your web server listens on ports 80 and 443 and those ports are open on your firewall, anyone (excluding blocked ips) can use his browser to view websites housed on your web server. Both ports 80 and 443 are open in this scenario.

Open ports can be a security issue since attackers can use them to exploit vulnerabilities or carry out other types of attacks. All other ports should be closed and just the ports required for your application’s operation should be exposed.

Check Open Ports with nmap

Nmap is a network scanning program capable of scanning both single hosts and big networks. It’s mostly used for penetration testing and security assessments.

When it comes to port scanning, nmap should be your first choice if it is available. Nmap can determine the Mac address, OS type, kernel versions, and much more in addition to port scanning.

Which ports are listening for TCP connections from the network can be determined by using the following command from the console:

The -sT option instructs nmap to scan for TCP ports, whereas the -p- option instructs it to scan for all 65535 ports. If the -p- option is not specified, nmap will only scan the 1000 most popular ports.

Output Starting Nmap 7.60 ( https://nmap.org ) at 2019-07-09 23:10 CEST Nmap scan report for 10.10.8.8 Host is up (0.0012s latency). Not shown: 998 closed ports PORT STATE SERVICE 22/tcp open ssh 80/tcp open http MAC Address: 08:00:27:05:49:23 (Oracle VirtualBox virtual NIC) Nmap done: 1 IP address (1 host up) scanned in 0.41 seconds 

Only ports 22 , 80 , and 8069 are open on the target system, according to the output.

Читайте также:  Стим клиент для линукс

Instead of -sT , use -sU to scan for UDP ports:

Visit the nmap man page for more information and to learn about all of this tool’s other useful features.

Check Open Ports with netcat

Netcat (or nc ) is a command-line utility that uses the TCP or UDP protocols to read and write data across network connections.

Netcat can scan a single port or a range of ports.

To search for open TCP ports on a distant system with IP address 10.10.8.8 in the range 20-80 , for example, execute the command:

The -z option instructs nc to scan only for open ports and not transfer any data, whereas the -v option provides more detailed information.

This is what the output will look like:

Output The -z option instructs nc to scan only for open ports and not transfer any data, whereas the -v option provides more detailed information. This is what the final product will look like: 

If you just want the lines with open ports written on the screen, use the grep command to filter the results.

nc -z -v 10.10.8.8 20-80 2>&1 | grep succeeded 
Output Connection to 10.10.8.8 22 port [tcp/ssh] succeeded! Connection to 10.10.8.8 80 port [tcp/http] succeeded! 

Pass the -u argument to the nc command to scan for UDP ports:

nc -z -v -u 10.10.8.8 20-80 2>&1 | grep succeeded 

Check Open Ports using Bash Pseudo Device

The Bash shell /dev/tcp/.. or /dev/udp/.. pseudo-device can also be used to determine whether a port is open or closed.

Bash will open a TCP or UDP connection to the specified host on the specified port when a command is run on a /dev/$PROTOCOL/$HOST/$IP pseudo-device.

The if..else statement below will check if port 443 on kernel.org is open:

if timeout 5 bash -c '/dev/null' then echo "Port is open" else echo "Port is closed" fi 

What is the purpose of the code above?

Because the default timeout when connecting to a port via a pseudo-device is so long, we’re utilizing the timeout command to kill the test command after 5 seconds. The test command will return true if the connection to kernel.org port 443 is established.

Use the for loop to check for a port range:

for PORT in ; do timeout 1 bash -c "/dev/null" && echo "port $PORT is open" done 

You will get an output like below:

Output port 22 is open port 80 is open 

Conclusion

We’ve taught you how to scan for open ports with a variety of tools. You can also check for open ports using other utilities and methods, such as the Python socket module, curl , telnet , or wget .

If you have any queries, please leave a comment below and we’ll be happy to respond to them.

Источник

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