提问人:SempriGno 提问时间:11/10/2023 最后编辑:xhienneSempriGno 更新时间:11/14/2023 访问量:48
将 netcat 的 stdinput 重定向到 bash 脚本的当前 stdout
Redirect stdinput of netcat to current stdout of bash script
问:
我有这个脚本:
#!/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
答:
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"
评论
bash
sh
{ echo hello; echo ...; } | nc localhost 100
exec {tcpsock}<>/dev/tcp/localhost/100; echo >&$tcpsock hello; read -u $tcpsock -r answer;echo $answer