Redirect process stdin and stdout to netcat

2019-04-02 08:11发布

I have an embedded linux application with a simple interactive command line interface.

I'd like to access the command line from telnet (or network, in general).

However, the process should be started when the board turns on, and in a unique instance. So, the following netcat command is not an option:

nc -l -p 4000 -e myapp

I can do

nc -l -p 4000 | myapp

to send remote commands to myapp, but this way I can't see myapp output.

Is there any way to redirect both stdin and stdout to netcat?

Thanks.

3条回答
聊天终结者
2楼-- · 2019-04-02 08:32

You can use ncat (from nmap package: apt install nmap) for that as well as follow:

ncat -lnvp 443 -e myapp

don't forget to fflush(stdout); after each printf("%s",str); in your app

查看更多
霸刀☆藐视天下
3楼-- · 2019-04-02 08:33

I found that by using bash v. >= 4.0 I can use coproc:

#!/bin/bash

coproc myapp
nc -kl -p 4000 <&"${COPROC[0]}" >&"${COPROC[1]}"
查看更多
男人必须洒脱
4楼-- · 2019-04-02 08:58

Is there a way to redirect both stdin and stdout to netcat

There is socat, which is a more advanced netcat. You can redirect both stdin and stdout with it. E.g.:

socat TCP4-LISTEN:5556,reuseaddr,fork EXEC:"cat - /etc/redhat-release"

In the above cat reads stdin and /etc/redhat-release and outputs them into stdout.

And then try using that:

$ echo "hello" | nc 127.0.0.1 5556
hello
Fedora release 22 (Twenty Two)

$ echo "hello 2" | nc 127.0.0.1 5556
hello 2
Fedora release 22 (Twenty Two)
查看更多
登录 后发表回答