Как я могу передать команды netcat, который останется живым?

77050
Chris
echo command | netcat host port 

В результате команда отправляется на удаленный хост, а некоторые данные считываются. Но через несколько секунд соединение закрывается. Параметр -w ничего не изменил. Я использую Netcat v1.10 на SuSE 10.1.

31
Вы уверены, что не удаленный хост закрывает соединение? grawity 13 лет назад 0
Yes. Doing netcat and then manually typing the command results in netcat staying alive indefinitely. Chris 13 лет назад 0
Почему он остался в живых? это просто напечатать параметры эха, а затем умереть? M'vy 13 лет назад 0
Я хочу, чтобы он оставался в живых, чтобы он продолжал получать данные, поступающие с удаленного сервера. Chris 13 лет назад 1
Если вы делаете это так, как написали, просто отправляете на удаленный сервер. Если вы хотите что-то получить, вам нужно открыть прослушивающий netcat на локальном компьютере. M'vy 13 лет назад 0
That's not true. "netcat " opens a bidirectional TCP socket. Chris 13 лет назад 2

8 ответов на вопрос

31
Chaitanya Gupta

Это работает с ncкомандой в OS X (при условии, что команда, которую вы хотите отправить, находится в файле):

cat file - | nc host port 

(По сути, catвыдает содержимое файла на стандартный вывод и затем ждет вас на стандартном вводе).

Если вы хотите отправить команду из самой оболочки, вы можете сделать это:

cat <(echo command) - | nc host port 
Это приятно, так как работает на очень простой встроенной системе, где netcat не хватает всех модных опций. SF. 7 лет назад 0
`` `` будет делать то же самое, и его можно будет легче понять. G-Man 6 лет назад 0
Как я вижу, команда `netcat` будет держать сокет открытым, пока не увидит конец ввода. Все эти примеры демонстрируют это, фактически не говоря много о _why_. Я взаимодействую с [`SocketTest`] (http://sockettest.sourceforge.net/) _server_, используя` netcat` в течение длительного периода, просто используя: `cat - | nc localhost 8063`. ** [SocketTest] (http://sockettest.sourceforge.net/) ** - это удобный инструмент, который может прослушивать или обслуживать любой порт TCP или UDP. will 6 лет назад 1
14
Georges Dupéron

With nc on Ubuntu:

nc -q -1 host port 

From the Ubuntu nc man page:

 -q seconds after EOF on stdin, wait the specified number of seconds and then quit. If seconds is negative, wait forever. 

Note that the available nc options vary a lot between distributions, so this might not work on yours (OpenSUSE).

11
Chris

I found it:

echo command | netcat host port - 

My coworker knew it. I don't see that in the documentation at all.

3
Majenko

I don't think you're going to manage this with either netcat or socat. I have just done extensive tinkering with both, and socat looked the most promising.

I managed to set socat up to connect to the remote TCP port and listen on a local unix domain socket (in theory so the link could be kept up all the time) but as soon as the local process detatched from the unix socket (another socat linking the unix socket to stdin/out) it closed the TCP socat session.

The problem here is that each connection through netcat / socat makes a new TCP stream connection to the server, and it closes that TCP stream session when the local end disconnects.

I think you're probably going to have to write some custom proxy software for this that opens the TCP connection to the remote end and then listens locally on a socket / pipe / fifo or whatever and then just sends the data down the existing TCP pipe and returns the results.

Послушай всемогущего Мэтта Дженкинса: D M'vy 13 лет назад 0
1
SF.

Метод Жоржа хорошо работает в интерактивной оболочке, но не поможет со сценариями, когда вы, например, вызываете свой сценарий как nohup ./script &.

Я нашел замену stdin на фиктивные подсказки fifo.

 mkfifo dummy cat command.txt dummy | nc host port 

Так как ничего не пишет в fifo, после вывода файла, catвисит на нем бесконечно.

1
Campa

Может ли быть так, что соединение закрыто на другом конце сокета?

По умолчанию ncзакрывает соединение после завершения, если вы явно не говорите ему, чтобы он продолжал слушать (с -kопцией):

 -k Forces nc to stay listening for another connection after its current connection is completed. It is an error to use this option without the -l option. 

См man nc.1.


Я успешно передаю данные между двумя машинами, например так:

  • отправитель:

    while (true); do  echo -n "$RANDOM " | nc <host> <port> done 
  • получатель:

    nc -kl <port> 
0
Jeremy

socat's shut-none option should help here:

Changes the (address dependent) method of shutting down the write part of a connection to not do anything.

You'll probably also need to override the default timeout period using -t <timeout>, otherwise the socket will be closed after 0.5s. This option overrides the default behaviour, which is:

When one of the streams effectively reaches EOF, the closing phase begins. Socat transfers the EOF condition to the other stream, i.e. tries to shutdown only its write stream, giving it a chance to terminate gracefully. For a defined time socat continues to transfer data in the other direction, but then closes all remaining channels and terminates.

So, a command such as:

echo 'blah' | socat -t 10 stdio tcp:<addr>:<port>,shut-none

will keep the socket open for 10s after sending the 'blah'.

0
allo

Your command terminates, if either the remote host closes the connection (or isn't reachable) or the command before the pipe is terminated (while netcat still sends the rest of its input queue).