【问题标题】:netcat to return the result of a command (run when connection happens)netcat 返回命令的结果(连接发生时运行)
【发布时间】:2021-02-19 07:32:20
【问题描述】:

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

这是一个简化的单 shell 示例。我希望 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

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

我尝试使用带有子外壳的“文件重定向”样式,但也不起作用。

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)

)

【问题讨论】:

  • 如果有人来到这里,想在创建连接时简单地运行命令,nc -c &lt;executable-path&gt; 就可以解决问题(尚未检查 返回的可能性 但是,命令的输出;并且某些nc 版本不支持-c-e 等)

标签: shell stdin netcat


【解决方案1】:

我想你想要这样的东西,我实际上是用 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

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

brew install socat

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-06
    • 2017-12-28
    • 2013-12-10
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多