Линукс проверить открыт ли порт

6 ways to Check a remote port is open in Linux

Checking remote port status is a common task for Linux admin. Now we collect 6 different ways for this task. We don’t need to install any package if we use the following two python commands. We need to install the package if we choose nc, nmap,telnet.

Methods to check if a remote port is open in Linux

The following commands can be used to check if a port is open on the remote server in Linux.

  • Use nc command nc -zvw10 192.168.0.1 22
  • Use nmap command nmap 192.168.0.1 -p 22
  • Use telnet command telnet 192.168.0.1 22
  • Use python telnet module
  • Use python socket module
  • Use curl command

Use nc command to check the remote port is open in Linux

$ nc [-options] [HostName or IP] [PortNumber]

  • z: zero-I/O mode which is used for scanning
  • v: for verbose output
  • w10: timeout wait 10 seconds

The “nc” command stands for “netcat”. The “nc” command is a very versatile command that can be used for a variety of purposes, including network administration and data transmission.

For example, the “nc” command can be used to create a simple TCP connection between two computers. The “nc” command can be used to connect to a remote server on a given port and send/receive data.

For example, if you want to connect to a remote server on port xx, you would use the following command: nc -zv port

In this example, “” is the IP address or hostname of the remote server, and “” is the port that you want to connect to.

I needed to see if the port 22 (SSH) on a remote machine was open, so I opened a terminal and ran the following command:

The -v option enabled verbose output, and the -z option instructed nc to only scan for open ports, without actually establishing a connection.

The output showed me the results of the port scan:

Connection to hostname.com 22 port [tcp/ssh] succeeded!

This told me that the port 22 was open and that I could connect to the remote machine using SSH.

In another scenario, if the port was not open, the output would look something like this:

Читайте также:  Intel hd graphics control panel linux

nc: connect to hostname.com port 22 (tcp) failed: Connection refused

You can also use the “nc” command to open a port in Linux. To do this, you would use the following command: nc -l -p 1234

In this example, “-l” is used to listen for a connection on port 1234

Use nmap to check the remote port is open in Linux

$ nmap [-options] [HostName or IP] [-p] [PortNumber]

The “nmap” command is a command-line tool used for network exploration and security auditing. The “nmap” command can be used to scan for open ports on a remote server, as well as to identify the operating system and services running on that server.

For example, if you want to scan for open ports on a remote server, you would use the following command:

In this example, “” is the IP address or hostname of the remote server, and “” is the port that you want to scan.

Use telnet to check the remote port is open in Linux

$ telnet [HostName or IP] [PortNumber]

The telnet command is a command-line tool used for network communication. The telnet command can be used to connect to a remote server on a given port.

For example, if you want to connect to a remote server on port, you would use the following command: telnet port

In this example, “” is the IP address or hostname of the remote server, and “” is the port that you want to connect to.

Use python telnet to check remote port is open in Linux

python -c «import telnetlib; tel=telnetlib.Telnet(‘192.168.0.1′,’22’,10); print tel; tel.close()»

If you are using Python3, using the following command:

python3 -c «import telnetlib; tel=telnetlib.Telnet(‘10.248.169.140′,’5432’,10); print(tel); tel.close()»

Telnetlib is a module in Python that allows you to communicate with remote servers using the Telnet protocol. The Telnet protocol is a text-based protocol used for communicating with remote servers.

To use the Telnetlib module, you first need to import it into your Python program: import telnetlib

Next, you need to create an instance of the Telnet object: telnet = telnetlib.Telnet()

The Telnet object has a number of methods that allow you to send and receive data. For example, the send() method allows you to send text data to the remote server, and the recv() method allows you to receive text data from the remote server.

Use python socket to check remote port is open in Linux

Python -c «import socket; s = socket.socket(); s.settimeout(10); s.connect((‘192.168.0.1’, 22)); «

The “socket” module is a module in Python that allows you to create and use sockets. A socket is a communication channel that allows two processes to connect and send/receive data.

The “socket” module has a number of functions that allow you to do a variety of things, including creating sockets, binding sockets to addresses, and sending/receiving data.

Читайте также:  Linux http 500 internal server error

In order to use the “socket” module, you first need to import it into your Python program. You can do this by using the following command: import socket

Once you have imported the “socket” module, you can then use its functions to create sockets and communicate with other processes.

Use curl to check remote port is open in Linux

We have another solution for this with the curl command. curl -v telnet://192.168.0.1:22

The “curl” command is a tool used for transferring data with URL syntax. The “curl” command can be used to send data to a remote server, or it can be used to download data from a remote server.

If you want to download data from a remote server, you can use the following command: curl port -o filename.txt

In this example, “” is the IP address or hostname of the remote server, and “” is the port that you want to download data from.

The “curl” command can also be used to check whether a port is open or not. To do this, you would use the following command:

In this example, “” is the IP address or hostname of the remote server, and “” is the port that you want to check.

Источник

Как посмотреть открытые порты в 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, поэтому работает быстрее и её данные более точные, если вы хотите выполнить просмотр открытых портов это не имеет большого значения. Опции у неё такие же:

Читайте также:  Linux remove all folders with name

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

3. lsof

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

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

4. Nmap

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

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

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

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

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

5. Zenmap

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

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

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

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

Выводы

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

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

Источник

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