Search code examples
bashtelnetnetcat

Bash: how to make telnet or nc work in background until connection is closed


Below I am describing what I was struggling with and the decision that I came to currently. Please point me to the cleverer/smaller decisions, also would be glad to receive feedback.

So, there are a publisher and a client on a localhost, they communicate through port 8080. I can telnet or nc to this port and write output to a log normally, but cannot make the same commands work in background.

What I see is that when launched in background they stop immediately after getting the first input (is it really so?), but in foreground they work as they should and die only after publisher closes connection at this port.

This is what occurs normally:

> telnet localhost 8080 | tee output.log (or >>output.log, no matter)
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Publisher starts sending information via port.

***some necessary output***

Publisher closes the port.

Connection closed by foreign host.

But when launched in background it stops immediately, without waiting for output:

> nohup telnet localhost 8080 | tee output.log (or <command> &, or nohup <command> &)
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.

Solution

  • You use a netcat command instead :

    nohup nc -d localhost 8080 >>console-8080.txt &
    

    If you want to indent the log file with the date :

    nohup nc -d localhost 8080 | while read line ; do echo `date +'%d%m%Y-%H%M%S'`: $line >>console-8080.txt; done &
    

    To restart nc process in case it closes :

    #!/bin/bash
    ip=$1
    port=$2
    while [ 1 ]
    do
        nc -d $ip $port | while read line ; do echo `date +'%d%m%Y-%H%M%S'`: $line >>console-$ip-$port.txt; done
        sleep .1
    done