Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send text file, line by line, with netcat

Tags:

shell

unix

netcat

I'm trying to send a file, line by line, with the following commands:

nc host port < textfile
cat textfile | nc host port

I've tried with tail and head, but with the same result: the entire file is sent as a unique line. The server is listening with a specific daemon to receive data log information.

I'd like to send and receive the lines one by one, not the whole file in a single shot.

How can I do that?

like image 623
Possa Avatar asked Dec 20 '12 10:12

Possa


4 Answers

Do you HAVE TO use netcat?

cat textfile > /dev/tcp/HOST/PORT

can also serve your purpose, at least with bash.


I'de like to send, and receive, one by one the lines, not all the file in a single shot.

Try

while read x; do echo "$x" | nc host port; done < textfile
like image 73
anishsane Avatar answered Oct 21 '22 06:10

anishsane


OP was unclear on whether they needed a new connection for each line. But based on the OP's comment here, I think their need is different than mine. However, Google sends people with my need here so here is where I will place this alternative.

I have a need to send a file line by line over a single connection. Basically, it's a "slow" cat. (This will be a common need for many "conversational" protocols.)

If I try to cat an email message to nc I get an error because the server can't have a "conversation" with me.

$ cat email_msg.txt | nc localhost 25
554 SMTP synchronization error

Now if I insert a slowcat into the pipe, I get the email.

$ function slowcat(){ while read; do sleep .05; echo "$REPLY"; done; }
$ cat email_msg.txt | slowcat | nc localhost 25
220 et3 ESMTP Exim 4.89 Fri, 27 Oct 2017 06:18:14 +0000
250 et3 Hello localhost [::1]
250 OK
250 Accepted
354 Enter message, ending with "." on a line by itself
250 OK id=1e7xyA-0000m6-VR
221 et3 closing connection

The email_msg.txt looks like this:

$ cat email_msg.txt
HELO localhost
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>
DATA
From: [IES] <[email protected]>
To: <[email protected]>
Date: Fri, 27 Oct 2017 06:14:11 +0000
Subject: Test Message

Hi there! This is supposed to be a real email...

Have a good day!
-- System


.
QUIT
like image 30
Bruno Bronosky Avatar answered Oct 21 '22 07:10

Bruno Bronosky


Use stdbuf -oL to adjust standard output stream buffering. If MODE is 'L' the corresponding stream will be line buffered:

stdbuf -oL cat textfile | nc host port
like image 4
Jirka Avatar answered Oct 21 '22 07:10

Jirka


Just guessing here, but you probably CR-NL end of lines:

sed $'s/$/\r/' textfile | nc host port
like image 2
glenn jackman Avatar answered Oct 21 '22 08:10

glenn jackman