Send text file, line by line, with netcat

牧云@^-^@ 提交于 2019-11-30 21:01:01

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

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:<system@example.com>
RCPT TO:<bbronosky@example.com>
DATA
From: [IES] <system@example.com>
To: <bbronosky@example.com>
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

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

sed $'s/$/\r/' textfile | nc host port

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!