简体   繁体   中英

How to modify input stream of netcat?

I'm creating a TCP/IP interface to a serial device on a redhat linux machine. netcat in a bash script was used to accomplish this with out to much trouble.

nc -l $PORT < $TTYDEVICE > $TTYDEVICE

The problem is that the serial device uses carriage returns('\\r') for line ends in its responses. I want to translate this to ("\\r\\n") so windows machines telneting in can view the response without any trouble. I'm trying to figure out how to go about this with a simple bash solution. I also have access to stty to configure the serial device, but there is no "\\r" to "\\r\\n" translate on the input side(from what I can tell).

I did try to use tr on the input side of netcat, but it didn't work.

#cat $TTYDEVICE | tr '\r' '\r\n' | nc -l $PORT > $TTYDEVICE

Any ideas?

Your problem is that the client that connects to $PORT probably does not have a clue that it is working with a tty on the other side, so you will experience issues with tty-specific "features", such as ^C/^D/etc. and CRLF.

That is why

socat tcp-listen:1234 - | hexdump -C
telnet localhost 1234
[enter text]

will show CRLFs, while

ssh -t localhost "hexdump -C"
[enter text]

yields pure LFs. Subsequently, you would eg need

ssh -t whateverhost "screen $TTYDEVICE"

tl;dr: netcat won't do it.

有多种版本的netcat(GNU和BSD),但您可能需要尝试:

 -C      Send CRLF as line-ending

This is overly difficult with standard tools, but pretty easy in perl (although perl is pretty much a standard tool these days):

perl -pe 's/\r/\r\n/g'

The version above will likely read the entire input into memory before doing any processing (it will read until it finds '\\n', which will be the entire input if the input does not contain '\\n'), so you might prefer:

perl -015 -pe '$\="\n"'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM