Проверить доступ к сети telnet и 6 способов проверить, открыт ли удаленный порт в Linux

Диагностика и логи

В этой статье мы расскажем:

  • что такое порт,
  • как проверить доступность порта через telnet,
  • для чего нужны команды ping и traceroute,
  • как диагностировать сеть с помощью MTR,
  • как посмотреть журнал сайта.

Что такое порт

Порт — это числовой идентификатор приложения или процесса в диапазоне от 0 до 65 535. На устройстве может находиться сразу несколько сетевых приложений, которые привязаны к разным портам, при этом за сеанс нужно подключиться только к одному приложению. Поэтому порт открывает соединение с конкретным приложением и обслуживает его, пока сеанс не завершится.

Проверить порт сервера на доступность можно следующими способами:

  • с помощью сервиса Проверка доступных портов,
  • с помощью консольных команд: telnet, ping, traceroute,
  • с помощью программы MTR.

Как проверить, открыт ли порт, командой Telnet

Рассмотрим, как узнать, открыт ли порт на компьютере или сервере в Windows и Linux.

Важно: в Windows Vista и Windows 7/8/10 утилита telnet по умолчанию отключена. Вы можете установить утилиту по инструкции от Microsoft.

  • Нажмите Пуск или сочетание клавиш Win + R.
  • В поле поиска введите «cmd» и нажмите кнопку ОК.
  • В командной строке введите команду:telnet имя_сервера номер_портаtelnet IP_сервера номер_портаЕсли командная строка или терминал возвращает ошибку, то порт закрыт:
    Как с помощью telnet в Windows 10 проверить портЕсли окно становится полностью пустым или на экране появляется приглашение сервера, порт открыт:

    Как выглядят в Windows и Linux (Ubuntu, Centos) открытые порты

  • Запустите терминал. Для этого в поисковой строке введите слово «Терминал» или нажмите комбинацию клавиш Ctrl+Alt+T.
  • Установите утилиту telnet:sudo apt install telnet
  • В терминале введите команду:telnet имя_сервера номер_портаtelnet IP_сервера номер_портаЕсли командная строка возвращает ошибку, то порт закрыт:
    Если порт открыт, появится следующее сообщение:

    Telnet: подключение к порту

Как пользоваться ping и traceroute

Traceroute — это утилита, с помощью которой можно отследить путь запроса к серверу, а также проблемы, связанные с доступностью удалённого сервера. Утилита отправляет запрос узлу и последовательно опрашивает все маршрутизаторы на пути. Подробнее о работе утилиты и её установке читайте в статье Утилиты Traceroute и Tracert.

Если у вас кириллический домен

Кириллические домены необходимо вводить в формате Punycode. Для перевода домена в Punycode воспользуйтесь сервисом. Введите имя вашего домена и нажмите Конвертировать.

Чтобы проверить доступность сайта или IP адреса, выберите инструкцию для вашей ОС.

  • Нажмите Пуск или сочетание клавиш Win + R.
  • В поле поиска введите «cmd» и нажмите кнопку ОК.
  • ping — ping имя_сайта или ping IP_сервера,

    Команда ping: как проверить доступность сервера или компьютера

  • Запустите терминал. Для этого в поисковой строке введите слово «Терминал» или нажмите комбинацию клавиш Ctrl+Alt+T.
  • В открывшемся окне терминала введите нужную команду:ping — ping имя_сайта или ping IP_сервера,

    traceroute — traceroute имя_сайта или traceroute IP_сервера.

  • ping — ping имя_сайта или ping IP_сервера,
  • traceroute — traceroute имя_сайта или traceroute IP_сервера.
  • Найдите в Spotlight утилиту Network Utility (Сетевая утилита) и запустите её.
  • В открывшейся программе выберите нужную вкладку:

Готово, мы рассмотрели, как пользоваться командой ping и как запустить tracert.

Результатом работы каждой из этих команд будет несколько строк в окне терминала. Результат команды ping покажет количество переданных и потерянных пакетов при обмене с узлом, а также время приёма и передачи. Результатом traceroute будет трассировка маршрута к узлу.

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

Диагностика сети при помощи MTR

MTR — программа, которая сочетает функционал команд traceroute и ping в одном инструменте. MTR проверяет соединение между локальной системой и указанным узлом (IP или доменом). Программа отправляет запрос к узлу, как команда ping, и показывает маршрут пакета, как traceroute.

Диагностика сети WinMTR:

  • Распакуйте архив и запустите программу от имени администратора:

    Centos: открытые порты

  • Нажмите Options, в настройках отключите галочку Resolve names. Нажмите OK:
  • Когда число отправленных пакетов (колонка «Sent») будет более 200, нажмите Stop:

    Диагностика сети Winmtr

  • Loss % — процент потерянных ответов от данного узла. Например, при «No response from host» процент потерь равен 100 — значит, маршрутизатор не ответил на ICMP-запрос;
  • Sent — количество отправленных запросов узлу;
  • Recv — количество полученных ответов от узла;
  • Best — наименьшее время задержки, мс;
  • Avrg — среднее время задержки, мс;
  • Worst — наибольшее время задержки, мс;
  • Last — время задержки последнего полученного пакета, мс.

На Linux утилита MTR установлена по умолчанию.

  • Запустите терминал. Для этого в поисковой строке введите слово «Терминал» или нажмите комбинацию клавиш Ctrl+Alt+T.
  • Если утилита MTR не установлена, введите команды:для Ubuntu/Debian: sudo apt install mtrдля CentOS: sudo yum install mtrдля Fedora: sudo dnf install mtr
  • для Ubuntu/Debian: sudo apt install mtr
  • для CentOS: sudo yum install mtr
  • для Fedora: sudo dnf install mtr
  • mtr -n -c 300 -r 123.123.123.123
  • Loss% — процент потерянных ответов от данного узла. Например, при «???» процент потерь равен 100 — значит, маршрутизатор не ответил на ICMP-запрос;
  • Snt — количество отправленных запросов узлу;
  • Last — время задержки последнего полученного пакета, мс;
  • Avg — среднее время задержки, мс;
  • Best — наименьшее время задержки, мс;
  • Wrst — наибольшее время задержки, мс;
  • StDev — среднеквадратичное отклонение времени задержки, мс.

В MacOS MTR не установлена по умолчанию. Чтобы установить MTR вручную:

  • Запустите терминал. Для этого нажмите Cmd + Пробел, в поисковой строке введите слово «Терминал» и нажмите Enter.
  • Если у вас не установлен пакетный менеджер Brew, установите его командой:Для выполнения команды укажите пароль пользователя. При успешном результате появится уведомление с текстом «Installation successful!»
  • Затем установите MTR командой:brew install mtr
  • После установки запустите MTR:sudo /usr/local/sbin/mtr yourdomain.comГде yourdomain.com — ваш домен. Для выполнения команды также потребуется ввести пароль пользователя.
  • Loss % — процент потерянных ответов от данного узла. Например, при «???» процент потерь равен 100 — значит, маршрутизатор не ответил на ICMP-запрос;
  • Snt — количество отправленных запросов узлу;
  • Last — время задержки последнего полученного пакета, мс;
  • Avg — среднее время задержки, мс;
  • Best — наименьшее время задержки, мс;
  • Wrst — наибольшее время задержки, мс;
  • StDev — среднеквадратичное отклонение времени задержки, мс.

Как просмотреть журналы сайтов

Журналы сайтов расположены в корневой директории хостинга в папке logs. Логи хостинга можно просмотреть как через хостинг-панели управления, так и по FTP и SSH. Подробнее о том, что такое логи, зачем они нужны и как их читать мы описали в статье Логи сервера.

В панели управления хостингом

Обратите внимание: если вид вашей панели управления отличается от представленного в статье, в разделе «Основная информация» переключите тему с paper_lantern на jupiter.

  • В разделе «Файлы» нажмите Менеджер файлов:
  • Кликните на папку logs:

По FTP или SSH

  • Перейдите в директорию logs:
  • Откройте необходимый файл журнала:
  • Введите команды cd logs и ls -all, чтобы посмотреть содержимое папки logs:
  • Откройте необходимый файл журнала.

Теперь вы знаете, как проверить, открыт ли порт на сервере, как использовать ping и traceroute, и как посмотреть логи сайта.

When it comes to checking if a network port is opened or closed on a remote computer, there’s no easier way than to use Telnet. Ports left open for no reason are a security risk that malicious programs and viruses can exploit. At the same time, if legitimate software communicates through a specific port, having that port closed will make the program throw errors and malfunction.

What is Telnet?

The name “Telnet” is short for “Teletype Network Protocol”.

In a nutshell, Telnet is a computer protocol that was built for interacting with remote computers. It enables terminal-to-terminal communication and can be used for a variety of purposes.

The word “Telnet” also refers to the command-line utility “telnet”, available under Windows OS and Unix-like systems, including Mac, Linux, and others. We will use the term “Telnet” mainly in the context of the telnet client software.

What is Telnet used for?

The Telnet protocol is as old-school as it gets in the tech world. It was developed in 1969, so it doesn’t pack the robust security features of today’s network protocols.

However, you can use Telnet to execute various other tasks. When properly connected, you can edit files, run programs, or check your email with it.

In addition, some servers enable remote Telnet connections to access public data. For starters, you can check the weather forecast via the Weather Underground service, active since 1995 and still running. (because, let’s face it, TV forecasts can get boring)

Moreover, Telnet lets you play chess at the Free Internet Chess Server and really merge with the spirit of old digital masters.

To play chess there, use the command:

Now, for the hardcore Star Wars fans – you can watch Star Wars Episode 4 in the default ASCII mode. Or at least the part of the movie that’s finished and available for “streaming”.

o towel.blinkenlights.nl 23

What are the 3 modes of Telnet protocol?

The Telnet protocol generally has three modes of operation. In all of them, your keyboard produces outgoing data via the Telnet command structure, travels via a Telnet TCP connection, and arrives at a virtual or physical terminal to satisfy a terminal-computer connection.

Telnet command section

Defined Telnet commands consist of:

WILL – 251 – Offer or accept to enable

WON’T – 252 – Accept of Offer to disable

DO – 253 – Request or Approve to enable operation

DON’T – 254 – Disapprove enable or Request to disable

SE – 240 – End of subnegotiation parameters

NOP – 241 – No operation

DM – 242- The Telnet command “data mark” indicates and locates a Telnet Synch sequence within the data stream. (critical to be accompanied by a Transmission Control Protocol (TCP) urgent notification)

BRK – 243 – Break command. It indicates that the “attention” or “break” key was hit

IP – 244 – Suspends, interrupts, or aborts the Network Virtual Terminal connection corresponding to the specific process

AO – 245 – Aborts output – allows for the process to complete but doesn’t send data

AYT – 246 – This stands for “Are you there?” – it requests to send back visible evidence that the AYT was received from the Network Virtual Terminal (NVT)

EC – 247 – Erase character command – the receiver of the command should delete the last undeleted preceding

EL – 248 – Erase line command – delete characters from the stream back to – but not including – the previous Carriage Return Line Feed (CRLF)

GA – 249 – The Telnet Go Ahead command – used primarily to inform the other end that it can start to transmit data

IAC – 255 – The “Interpret-as-command” character

Telnet protocol command options

Several Telnet option specifications are available to negotiate between the Telnet client and server. This can be done by using commands at any stage as long as the connection persists. Below is a list of the most important command options.

Actual code assignments

3 suppress go ahead

6 timing mark

24 terminal type

31 window size

32 terminal speed

33 remote flow control

36 environment variables

Options undergo a negotiation process to present the client and server with a common view of the potential extra capabilities affecting the interchange and the operation of applications.

Both ends of a Telnet dialogue can either enable or disable options locally or remotely.

How to enable a Telnet connection on a server?

The Telnet client is built into Windows 11, but to use it on Windows Server 2022, you’d need to enable it as it’s disabled by default.

  • Open “Server Manager” from the Start menu
  • In the “Add Roles and Features Wizard”, select “Next” on the “Before you begin” line
  • Click “Next” on the “Select server roles” line
  • Select “Install” on the “Confirmation installation selections” line
  • Close the “Add Roles and Features Wizard”

The Telnet protocol can be enabled in several ways. Below, we will explore all available options so that you can choose the most efficient one for you.

Enabling Telnet client in Microsoft Windows operating systems

As we’ve mentioned, Telnet is disabled by default in Windows settings, so you need to turn it on before you can do anything. Enabling it will help you run the required diagnostics and check if a port is open. If you try to use Telnet without turning it on first, you’ll receive a message like this:

In order to turn Telnet on, you need to use the command line or the graphical interface of your computer.

Enabling Telnet client through Command Prompt

Dism /Online /Enable-feature /FeatureName:TelnetClient

After you’ve put this in, Telnet will be ready to use to check your ports.

Install-WindowsFeature -name Telnet-Client

How to enable Telnet client on Windows 7, 8

For example, to verify connection to 192.168.0.10 on port 25, issue the command:

telnet 192.168.0.10 25

If the connection succeeds, a blank screen will appear, meaning that the computer port is open.

A failed connection will be accompanied by an error message. Such a signal can indicate either a closed port or that the indicated remote server is not listening on the provided port.

Example

Проверить доступ к сети telnet и 6 способов проверить, открыт ли удаленный порт в Linux

Testing open ports with Telnet

Проверить доступ к сети telnet и 6 способов проверить, открыт ли удаленный порт в Linux

How to Check if a Port is Open on Mac

When a computer port is open, a blank screen will show up, meaning that the connection has been successful. An unsuccessful connection will be accompanied by an error message.

Acting on the results obtained from the Telnet test

If you want to check for closed ports on your router, enter your router management console. Open a web browser and enter the IP address or name of the router, for example, “192.168.0.10”. If the page does not open, try replacing “http” with “https” at the beginning of the address.

If you need to make resources in the internal network accessible from the outside, enter “External access”/” Port forwarding” section. Consult the router manufacturer’s documentation for detailed instructions.

What is SSH? What is its port?

SSH stands for “Secure Shell” or “Secure Socket Shell”. It’s a secure protocol that enables encrypted communication between two computers.

As SSH enables encrypted communication between the two machines, it is suitable for unsecured networks.

SSH is primarily used to establish a virtual terminal connection and log onto a remote machine to perform operations or transfer data. The default port for the SSH client connection is 22. You can change the default by entering a port number between 1024 and 32,767.

How does SSH work?

To establish remote terminal access via Secure Shell, you’d need an SSH client on your computer to connect to the SSH server.

The SSH client, once enabled, invokes the connection setup process to process communication secured by strong symmetric encryption.

What is the difference between Telnet and SSH?

Telnet and SSH are both network protocols used to manage a remote computer system.

But what makes them different? Let’s explore that below step-by-step.

Telnet requires a server app installed on the remote computer (the one you want to manage) and a client app installed on the local machine.

Telnet uses the TCP port protocol and port 23 to establish a connection with remote computers. The created system acts as a Telnet server and is available to receive commands. Said commands are sent via the Network Virtual Terminal (NVT) format. Then, they are received and interpreted by the Telnet server and sent to the corresponding application.

SSH ensures a secure connection to the server via port 22. It generates a session after the client verifies the server via key-based authentication. The generated session is sent to both the client and the server, and all traffic is encrypted for the current session.

Lastly, the server verifies the client via a generated SSH key pair. After successful client authentication, it establishes an encrypted connection, and the two systems can exchange data securely.

Telnet doesn’t provide any security features or protocols when transmitting data. The network protocol is highly vulnerable to cyber threats unless used on private, trusted, preferably offline, networks.

Thanks to the key pairs used for authentication, SSH is extremely difficult to penetrate and read the transferred data. This makes it a way more secure protocol than Telnet, even for unsecured networks.

Telnet sends data as plain text via the NVT format.

SSH sends data via an encrypted format through a secure channel.

Telnet employs no authentication mechanism.

SSH relies on public key encryption.

Both Telnet and SSH are available on Windows, Mac OS, and Linux. (with some exceptions for Telnet in newer Mac OS versions)

Telnet connection bandwidth usage is low.

SSH connection bandwidth usage is high.

When to use Telnet or SSH?

There are two primary cases when using a Telnet connection over SSH is recommended.

  • When operating on trusted networks (e.g., LANs) that are disconnected from the internet.
  • When operating with a remote host that doesn’t support SSH.

In all other cases, it’s best to use SSH since it provides high security for internet-connected devices.

In addition, SSH enables more functionality options than Telnet. (e.g., secure file transfer, port forwarding)

Is Telnet still used?

Telnet is a primordial being in the tech universe. And as such, it is still being used in specific scenarios. Telnet is easy to operate, requires no high-tech knowledge, and doesn’t overload your network. (in most cases)

Related Acronis resources

Read further on what ports are used in Acronis software and how to open them:

https://kb.acronis.com/brandmauer – A summary page about the network ports used in Acronis software

Performing a test with the telnet client

Now that the telnet client is installed (see my last post here if you have not done this yet) we can perform some basic network connectivity tests. The command is used in the format of ‘telnet hostname/ip address port‘ and entered into either command prompt or powershell under Windows, or through the shell in Linux or Unix. For example we can enter the below command to attempt connect to google.com on port 80:

After entering that into your blank telnet session you will not see any output until you press enter, at this point you should see a response from the web server. Although this is a basic test, if the session goes blank it confirms that we can establish a TCP connection on port 80 to the web server meaning there is likely a web server running on the remote host accepting our connections. Even better if we get a response to our GET command as this can confirm if the web server is responding and behaving as expected.

What if I get no response?

On the other hand if the telnet session does not succeed and fails to connect you may get output similar to the below.

In this example I’m trying to connect to google.com on a random port 1111, however it fails, what could be the problem?

The remote server might not be listening on that port: The server you’re trying to connect to might not have any services listening on the port you’re trying to connect on, in this instance it will not respond and the connection will fail as it’s not expecting connections on the port. If you have access to the remote server you could run a command such as ‘netstat’ to get an idea of what ports the server is listening on and accepting connections for.

Summary

As you can see there are plenty of reasons a telnet connection may or may not succeed, however being able to test this by enabling the telnet tool has allowed us to perform additional troubleshooting steps to get an idea of where potential connectivity problems may lie.

This page contains detailed information about how to use the auxiliary/scanner/telnet/telnet_login metasploit module. For list of all metasploit modules, visit the Metasploit Module Library.

Module Overview

Name: Telnet Login Check Scanner
Module: auxiliary/scanner/telnet/telnet_login
Source code: modules/auxiliary/scanner/telnet/telnet_login.rb
Disclosure date: –
Last modification time: 2021-08-31 17:10:07 +0000
Supported architecture(s): –
Supported platform(s): –
Target service / protocol: telnet
Target network port(s): 23
List of CVEs: CVE-1999-0502

This module will test a telnet login on a range of machines
and report successful logins. If you have loaded a database
plugin and connected to a database this module will record
successful logins and hosts so you can track your access.

Module Ranking and Traits

This module is a scanner module, and is capable of testing against multiple hosts.

Other examples of setting the RHOSTS option:

Required Options

  • Do: use auxiliary/scanner/telnet/telnet_login
  • Do: run

Only one password to authenticate with.

USERPASS_FILE

File containing passwords one per line.

Scenarios

Go back to menu.

Msfconsole Usage

Here is how the scanner/telnet/telnet_login auxiliary module looks in the msfconsole:

Module Options

This is a complete list of options available in the scanner/telnet/telnet_login auxiliary module:

Advanced Options

Here is a complete list of advanced options supported by the scanner/telnet/telnet_login auxiliary module:

Auxiliary Actions

This is a list of all auxiliary actions that the scanner/telnet/telnet_login module can do:

Evasion Options

Here is the full list of possible evasion options supported by the scanner/telnet/telnet_login auxiliary module in order to evade defenses (e.g. Antivirus, EDR, Firewall, NIDS etc.):

Check for the possible causes from the code snippets below found in the module source code. This can often times help in identifying the root cause of the problem.

<RESULT. CREDENTIAL> (<RESULT. STATUS>

Related Nessus plugins:

Version

  • 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 -zvw10 192.168.0.1 22

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

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.

$ nc -vz hostname.com 22

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:

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:

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

Use nmap to check the remote port is open in Linux

nmap 192.168.0.1 -p 22

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.

Use telnet to check the remote port is open in Linux

telnet 192.168.0.1 22

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.

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()”

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.

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.

Understanding TCP Connection with Examples

4 Ways to Check Network Status on Linux

Linux Learning Guide:

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

Эта утилита очень часто использовалась раньше, для удаленного управления компьютером с Linux, но потом ей на замену пришел защищенный протокол SSH. Но telnet все еще используется, например, для тестирования сети, проверки портов, а также для взаимодействия с различными IoT устройствами и роутерами. В этой статье мы рассмотрим что такое telnet, а также как пользоваться telnet для решения своих задач.

  • Что такое Telnet?
  • Как пользоваться telnet?
  • Выводы

Как я уже сказал, эта утилита предназначена для создания интерактивного соединения между удаленными компьютерами. Она работает по протоколу TELNET, но этот протокол поддерживается многими сервисами, поэтому ее можно использовать для управления ими. Протокол работает на основе TCP, и позволяет передавать обычные строковые команды на другое устройство. Он может использоваться не только для ручного управления но и для взаимодействия между процессами.

Для работы с этим протоколом мы будем использовать утилиту telnet, ею очень просто пользоваться. Давайте рассмотрим синтаксис telnet:

Хост – это домен удаленного компьютера, к которому следует подключиться, а порт – порт на этом компьютере. А теперь давайте рассмотрим основные опции:

  • -4 – принудительно использовать адреса ipv4;
  • -6 – принудительно использовать адреса ipv6;
  • -8 – использовать 8-битную кодировку, например, Unicode;
  • -E – отключить поддержку Escape последовательностей;
  • -b – использовать локальный сокет;
  • -d – включить режим отладки;
  • -р – режим эмуляции rlogin;
  • -e – задать символ начала Escape последовательности;
  • -l – пользователь для авторизации на удаленной машине.

Это все, что касается команды telnet для установки соединения. Но соединение с удаленным хостом, это только полдела. После установки подключения telnet может работать в двух режимах:

Использование telnet заключается в передаче специальных команд. У каждого сервиса свои команды, но у протокола есть свои команды telnet, которые можно применять в консоли telnet.

  • CLOSE – закрыть соединение с сервером;
  • ENCRYPT – шифровать все передаваемые данные;
  • LOGOUT – выйти и закрыть соединение;
  • MODE – переключить режим, со строчного на символьный или с символьного на строчный;
  • STATUS – посмотреть статус соединения;
  • SET – установить значение параметра;
  • OPEN – установить подключение через telnet с удаленным узлом;
  • DISPLAY – отобразить используемые спецсимволы;
  • SLC – изменить используемые спецсимволы.

Мы не будем рассматривать все команды, поскольку они вам вряд ли понадобятся, а если и понадобятся, то вы легко сможете их найти в официальной документации.

Как пользоваться telnet?

Дальше мы рассмотрим как использовать telnet для решения ваших задач. Обычно, утилита уже установлена в большинстве систем, но если это не так, то вы можете установить telnet из официальных репозиториев, например, в Ubuntu:

sudo apt install telnet

Теперь перейдем к применению утилиты. Изначально она использовалась для удаленного управления компьютером, но поскольку потом был разработан более безопасный протокол SSH, использовать ее перестали.

Доступность сервера

Утилита все еще может быть полезной при поверке доступности узла, для этого просто передайте ей ip адрес или имя хоста:

Проверить доступ к сети telnet и 6 способов проверить, открыт ли удаленный порт в Linux

Для этого не обязательно применять telnet, есть ping.

Проверка порта

C помощью telnet мы можем проверить доступность порта на узле, а это уже может быть очень полезным. Чтобы проверить порт telnet выполните:

telnet localhost 123
$ telnet localhost 22

Проверить доступ к сети telnet и 6 способов проверить, открыт ли удаленный порт в Linux

В первом случае мы видим, что соединение никто не принимает, во втором же выводится сообщение об успешном подключении и приветствие SSH сервера.

Отладка

sudo telnet -d localhost 22

Консоль telnet

Проверить доступ к сети telnet и 6 способов проверить, открыт ли удаленный порт в Linux

Чтобы посмотреть все доступные команды, вы можете набрать ?. Например, вы можете посмотреть статус подключения:

Проверить доступ к сети telnet и 6 способов проверить, открыт ли удаленный порт в Linux

Здесь есть и другие интересные возможности. Такие вещи можно проделывать при любом подключении с помощью утилиты telnet.

Посмотреть сайт telnet

Один из распространенных способов использования telnet – это тестирование сайта из консоли. Да, красивую веб-страницу вы не получите, но можете вручную собрать запросы и видеть все переданные сервером данные.

Затем наберите команду веб-серверу:

Проверить доступ к сети telnet и 6 способов проверить, открыт ли удаленный порт в Linux

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

Удаленное управление telnet

Настоятельно не рекомендуется использовать небезопасный telnet для удаленного управления, потому что все команды и пароли могут быть прослушаны сторонним пользователем. Но иногда, например, для роутеров telnet все же используется для удаленного управления. Все работает точно так же, как и для других подключений, только нужно использовать порт 23, а на удаленном компьютере должен быть установлен telnet-server:

telnet localhost 23

:/>  Разгоняем Windows 10: как включить максимальный режим -