netcat返回命令结果(在发生连接时运行)

时间:2020-11-06 14:49:45

标签: shell stdin netcat

我想使用netcat返回服务器上命令的结果。但是这是技巧,我希望在建立连接时运行命令。当我启动netcat时没有。

这里是一个简化的单外壳示例。我希望ls在我连接到1234时运行(通常我会从远程服务器执行此操作,显然,此示例毫无意义,我可以在本地执行ls)

max $ ls | nc -l 1234 &
[1] 36685
max $ touch file
max $ nc 0 1234
[1]+  Done                    ls | nc -l 1234
max $ ls | nc -l 1234 &
[1] 36699
max $ rm file
max $ nc 0 1234
file
[1]+  Done                    ls | nc -l 1234

您可以看到ls在我启动监听器时运行,而不是在我连接到它时运行。因此,在第一个实例中,当我启动并创建文件时没有文件,然后建立连接,并且在侦听命令启动时(空)报告了文件系统的状态,而不是当前状态。 file消失后的第二次显示它仍然存在。

类似于从文件重定向时的工作方式。例如:

max $ touch file
max $ nc -l 1234 < file &
[1] 36768
max $ echo content > file
max $ nc 0 1234
content
[1]+  Done                    nc -l 1234 < file

远程连接获取文件的最新内容,而不是侦听命令启动时的内容。

我尝试将“文件重定向”样式与子外壳一起使用,但这也不起作用。

max $ nc -l 1234 < <(cat file) &
[1] 36791
max $ echo bar > file
max $ nc 0 1234
content
[1]+  Done                    nc -l 1234 < <(cat file)

我唯一能想到的就是将我的command |netcat添加到xinetd.conf / systemd中。我可能还是不得不将其作为服务添加到systemd中。

(实际上,我想做的是:将VPN用户列表提供给网络端口,以供远程服务获取当前用户列表。我生成列表的命令如下:

awk '/Bytes/,/ROUTING/' /etc/openvpn/openvpn-status.log | cut -f1 -d. | tail -n +2 | tac | tail -n +2 | sort -b | join -o 2.2 -j1 - <(sort -k1b,1 /etc/openvpn/generate-new-certs.sh)

1 个答案:

答案 0 :(得分:0)

我认为您想要这样的东西,而我实际上是用socat做的:

# Listen on port 65500 and exec '/bin/date' when a connection is received
socat -d -d -d TCP-LISTEN:65500 EXEC:/bin/date

几秒钟后,在另一个终端:

echo Hi | nc localhost 65500

注意:对于 macOS 用户,您可以使用 homebrew 安装socat

brew install socat