Netcat linux как пользоваться

Netcat linux как пользоваться

NAME

nc - TCP/IP swiss army knife

SYNOPSIS

nc [-options] hostname port[s] [ports] . nc -l -p port [-options] [hostname] [port] 

DESCRIPTION

netcat is a simple unix utility which reads and writes data across network connections, using TCP or UDP protocol. It is designed to be a reliable "back-end" tool that can be used directly or easily driven by other programs and scripts. At the same time, it is a feature-rich network debugging and exploration tool, since it can create almost any kind of connection you would need and has several interesting built-in capabilities. Netcat, or "nc" as the actual program is named, should have been supplied long ago as another one of those cryptic but standard Unix tools. In the simplest usage, "nc host port" creates a TCP connection to the given port on the given target host. Your standard input is then sent to the host, and anything that comes back across the connection is sent to your standard output. This continues indefinitely, until the network side of the connection shuts down. Note that this behavior is different from most other applications which shut everything down and exit after an end-of-file on the standard input. Netcat can also function as a server, by listening for inbound connections on arbitrary ports and then doing the same reading and writing. With minor limitations, netcat doesn't really care if it runs in "client" or "server" mode -- it still shovels data back and forth until there isn't any more left. In either mode, shutdown can be forced after a configurable time of inactivity on the network side. And it can do this via UDP too, so netcat is possibly the "udp telnet-like" application you always wanted for testing your UDP-mode servers. UDP, as the "U" implies, gives less reliable data transmission than TCP connections and some systems may have trouble sending large amounts of data that way, but it's still a useful capability to have. You may be asking "why not just use telnet to connect to arbitrary ports?" Valid question, and here are some reasons. Telnet has the "standard input EOF" problem, so one must introduce calculated delays in driving scripts to allow network output to finish. This is the main reason netcat stays running until the *network* side closes. Telnet also will not transfer arbitrary binary data, because certain characters are interpreted as telnet options and are thus removed from the data stream. Telnet also emits some of its diagnostic messages to standard output, where netcat keeps such things religiously separated from its *output* and will never modify any of the real data in transit unless you *really* want it to. And of course telnet is incapable of listening for inbound connections, or using UDP instead. Netcat doesn't have any of these limitations, is much smaller and faster than telnet, and has many other advantages.

OPTIONS

-c string specify shell commands to exec after connect (use with caution). The string is passed to /bin/sh -c for execution. See the -e option if you don't have a working /bin/sh (Note that POSIX-conformant system must have one). -e filename specify filename to exec after connect (use with caution). See the -c option for enhanced functionality. -g gateway source-routing hop point[s], up to 8 -G num source-routing pointer: 4, 8, 12, . -h display help -i secs delay interval for lines sent, ports scanned -l listen mode, for inbound connects -n numeric-only IP addresses, no DNS -o file hex dump of traffic -p port local port number (port numbers can be individual or ranges: lo-hi [inclusive]) -q seconds after EOF on stdin, wait the specified number of seconds and then quit. If seconds is negative, wait forever. -b allow UDP broadcasts -r randomize local and remote ports -s addr local source address -t enable telnet negotiation -u UDP mode -v verbose [use twice to be more verbose] -w secs timeout for connects and final net reads -z zero-I/O mode [used for scanning] -T type set TOS flag (type may be one of "Minimize-Delay", "Maximize-Throughput", "Maximize-Reliability", or "Minimize-Cost".)

NOTES

Some port names in /etc/services contain hyphens -- netcat currently will not correctly parse those unless you escape the hyphens with backslashes (e.g. "netcat localhost 'ftp\-data'").

BUGS

Efforts have been made to have netcat "do the right thing" in all its various modes. If you believe that it is doing the wrong thing under whatever circumstances, please notify me and tell me how you think it should behave. If netcat is not able to do some task you think up, minor tweaks to the code will probably fix that. It provides a basic and easily-modified template for writing other network applications, and I certainly encourage people to make custom mods and send in any improvements they make to it. Continued feedback from the Internet community is always welcome!

EXAMPLES

For several netcat recipes, please see /usr/share/doc/netcat/README.gz and /usr/share/doc/netcat/README.Debian.gz.

AUTHOR

This manual page was written by Joey Hess joeyh@debian.org> and Robert Woodcock rcw@debian.org>, cribbing heavily from Netcat's README file. Netcat was written by a guy we know as the Hobbit hobbit@avian.org>. NC(1)

© 2019 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd.

Читайте также:  Yum and rpm in linux

Источник

Команда Netcat (nc) с примерами

Netcat (или nc ) — это утилита командной строки, которая считывает и записывает данные через сетевые соединения с использованием протоколов TCP или UDP. Это один из самых мощных инструментов в арсенале сетевых и системных администраторов, который считается швейцарским армейским ножом сетевых инструментов.

Netcat является кроссплатформенным и доступен для Linux, macOS, Windows и BSD. Вы можете использовать Netcat для отладки и мониторинга сетевых подключений, сканирования открытых портов, передачи данных в качестве прокси-сервера и многого другого.

Пакет Netcat предварительно установлен в macOS и популярных дистрибутивах Linux, таких как Ubuntu, Debian или CentOS.

Синтаксис Netcat

Самый простой синтаксис утилиты Netcat имеет следующий вид:

В Ubuntu вы можете использовать netcat или nc . Оба они являются символическими ссылками на версию Netcat для openBSD.

По умолчанию Netcat пытается запустить TCP-соединение с указанным хостом и портом. Если вы хотите установить UDP-соединение, используйте параметр -u :

Сканирование портов

Сканирование портов — одно из самых распространенных применений Netcat. Вы можете сканировать один порт или диапазон портов.

Например, чтобы сканировать открытые порты в диапазоне 20-80, вы должны использовать следующую команду:

Опция -z укажет nc сканировать только открытые порты, не отправляя им никаких данных, а опция -v предоставит более подробную информацию.

Результат будет выглядеть примерно так:

nc: connect to 10.10.8.8 port 20 (tcp) failed: Connection refused nc: connect to 10.10.8.8 port 21 (tcp) failed: Connection refused Connection to 10.10.8.8 22 port [tcp/ssh] succeeded! nc: connect to 10.10.8.8 port 23 (tcp) failed: Connection refused . nc: connect to 10.10.8.8 port 79 (tcp) failed: Connection refused Connection to 10.10.8.8 80 port [tcp/http] succeeded! 

Если вы хотите распечатать только строки с открытыми портами, вы можете отфильтровать результаты с помощью команды grep .

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

Вы также можете использовать Netcat для поиска серверного программного обеспечения и его версии. Например, если вы отправляете команду «EXIT» на сервер через SSH-порт 22 по умолчанию:

Читайте также:  Смонтировать виртуальный диск linux

Результат будет выглядеть примерно так:

SSH-2.0-OpenSSH_7.6p1 Ubuntu-4 Protocol mismatch. 

Чтобы сканировать порты UDP, просто добавьте к команде параметр -u как показано ниже:

Как правило, Nmap — лучший инструмент, чем Netcat для комплексного сканирования портов.

Отправка файлов через Netcat

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

Это работает путем настройки Netcat для прослушивания определенного порта (с использованием параметра -l ) на принимающем хосте, а затем установления обычного TCP-соединения с другим хостом и отправки файла через него.

При получении выполните следующую команду, которая откроет порт 5555 для входящего соединения и перенаправит вывод в файл:

От отправляющего хоста подключитесь к принимающему хосту и отправьте файл:

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

На принимающем хосте настройте инструмент Netcat для прослушивания входящего соединения через порт 5555. Входящие данные передаются команде tar , которая распаковывает архив:

На передающем хосте упакуйте каталог и отправьте данные, подключившись к слушающему процессу nc на принимающем хосте:

tar czvf - /path/to/dir | nc receiving.host.com 5555

Вы можете наблюдать за процессом передачи на обоих концах. По завершении CTRL+C чтобы закрыть соединение.

Создание простого чат-сервера

Процедура создания онлайн-чата между двумя и более хостами такая же, как и при передаче файлов.

На первом хосте запустите процесс Netcat для прослушивания порта 5555:

Со второго хоста выполните следующую команду для подключения к слушающему порту:

Теперь, если вы наберете сообщение и нажмете ENTER оно будет отображаться на обоих хостах.

Чтобы закрыть соединение, введите CTRL+C

Выполнение HTTP-запроса

Хотя есть гораздо лучшие инструменты для HTTP-запросов, такие как curl , вы также можете использовать Netcat для отправки различных запросов на удаленные серверы.

Читайте также:  Killing jobs in linux

Например, чтобы получить справочную страницу Netcat с веб-сайта OpenBSD, вы должны ввести:

printf "GET /nc.1 HTTP/1.1rnHost: man.openbsd.orgrnrn" | nc man.openbsd.org 80

Полный ответ, включая заголовки HTTP и HTML-код, будет напечатан в терминале.

Выводы

В этом руководстве вы узнали, как использовать утилиту Netcat для установления и тестирования соединений TCP и UDP.

Для получения дополнительной информации посетите страницу руководства Netcat и прочтите обо всех других мощных параметрах команды Netcat.

Если у вас есть вопросы или замечания, пожалуйста, оставьте комментарий ниже.

Источник

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