关于shell:使用netcat逐行发送文本文件

Send text file, line by line, with netcat

我正在尝试使用以下命令逐行发送文件:

1
2
nc host port < textfile
cat textfile | nc host port

我尝试使用尾巴和头部,但结果相同:整个文件以唯一行的形式发送。
服务器正在侦听特定的守护程序以接收数据日志信息。

我想一次一行地发送和接收行,而不是一次发送整个文件。

我该怎么做?


您必须使用netcat吗?

1
cat textfile > /dev/tcp/HOST/PORT

至少可以通过bash达到您的目的。

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

尝试

1
while read x; do echo"$x" | nc host port; done < textfile


OP不清楚他们是否需要为每条线建立新的连接。但是基于OP在这里的评论,我认为他们的需求与我的不同。但是,Google会将有我需要的人发送到这里,因此我将在这里放置此替代项。

我需要通过单个连接逐行发送文件。基本上,它是"慢" cat。 (这将是许多"对话"协议的普遍需求。)

如果我尝试向nc发送电子邮件,则会收到错误消息,因为服务器无法与我进行"对话"。

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

现在,如果我在管道中插入slowcat,我会收到电子邮件。

1
2
3
4
5
6
7
8
9
$ 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

email_msg.txt看起来像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ 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


使用stdbuf -oL调整标准输出流缓冲。如果MODE为'L',则相应的流将被行缓冲:

1
stdbuf -oL cat textfile | nc host port

这里只是猜测,但您可能是CR-NL行尾:

1
2
sed $'s/$/\
/' textfile | nc host port