将 netcat 的 stdinput 重定向到 bash 脚本的当前 stdout

Redirect stdinput of netcat to current stdout of bash script

提问人:SempriGno 提问时间:11/10/2023 最后编辑:xhienneSempriGno 更新时间:11/14/2023 访问量:48

问:

我有这个脚本:

#!/bin/bash
exec 4>&1
nc localhost 100 0<&4 &
echo hello 
echo ....

我只想向 netcat 发送 hello 和其他内容,但这种方法不起作用。 我知道有效,但我不需要它,同样。 命名管道也可以,但我想知道是否可以实现上述简单的事情。echo "hello" | nc localhost"nc localhost 0<file.txt echo "hello" >file.txt

bash io-重定向

评论

0赞 Barmar 11/11/2023
这是行不通的。文件描述符不是双向的 -- 从中读取不会读取写入它的内容。
1赞 Barmar 11/11/2023
你同时拥有 和 标签 -- 它们不一样,选择一个。bashsh
0赞 Philippe 11/11/2023
你试过吗?{ echo hello; echo ...; } | nc localhost 100
0赞 F. Hauri - Give Up GitHub 11/12/2023
bash 下,你可以exec {tcpsock}<>/dev/tcp/localhost/100; echo >&$tcpsock hello; read -u $tcpsock -r answer;echo $answer

答:

1赞 xhienne 11/14/2023 #1

我建议你试试 Bash 的协进程:

coproc nc ( netcat localhost 100 )

上述命令在后台启动,并将其标准输入链接到文件描述符,并将其标准输出链接到 。netcat${nc[1]}${nc[0]}

然后,您可以操作这些文件描述符以替换当前的 stdin 和 stdout:

#!/bin/bash
coproc nc ( netcat localhost 100 )

# Current stdin and stdout are saved in old_stdin and old_stdout,
# then they are replaced with the input and output of the coprocess
exec {old_stdin}<&0 {old_stdout}>&1 <&${nc[0]} >&${nc[1]}

echo "This is sent to netcat"
read reply

# We restore the former stdin and stdout
exec <&$old_stdin >&$old_stdout
echo "This was received from netcat: $reply"