Search code examples
bashubuntu-14.04terminatenetcat

How can I terminate netcat so my script can loop again?


I'm running a bash script that goes through the list of my remote server IPs, connects via netcat (telnet) for each line, and runs a few commands.

The problem is I can't seem to figure out how to terminate netcat so the script can loop to the next IP in the list.

Here's the relevant bit:

#!/bin/bash
while ISF= read -r line;do
(
sleep 3
printf 'command1'
sleep 3
printf 'command2'
sleep 3
) | nc $line
done < ~/servers.txt

The remote servers don't send an EOF, so is there something I can echo or printf at netcat to terminate netcat so the script can loop through again? I would really rather not do a -w flag for a timeout, because I have quite a few servers I need to do this on, and a timeout would make it take much longer.


Solution

  • Specify a timeout after which nc will exit if it receives no further input, either from the remote end or via standard input.

    ... | nc "$line" -w 10   # Choose a value for -w as appropriate