Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to open a netcat connection and keep sending some text forever

Tags:

bash

netcat

echo " The NC send commands  on port 2612"
while :
do
echo "hello " | nc -q -1  <some IP> 2612 
done

I want open a netcat session forever, and that is been achived by -q -1.

How can I send "hello" on the same channed in every 20 second.

my earlier script was as following, but that opens nc connection every time. What I really want is to open connection once and send "echo hello" evey 20 sec.

while :
do
echo "hello " | nc  192.168.100.161 2612 
sleep 20 
done
like image 536
EveryProblemHasSolution Avatar asked Oct 24 '25 03:10

EveryProblemHasSolution


1 Answers

while echo "hello"; do
  sleep 20
done | nc -q 192.168.100.161 2612

Note that we moved the echo into the condition of the loop, so that we stop trying to run it if nc exits (causing the echos to fail).


If you want to be able to retain state (for instance, a counter) from inside the loop and access it after the pipeline exited, then things need to change a bit further:

#!/bin/bash
#      ^^^^- process substitutions aren't part of POSIX sh

count=0
while echo "hello"; do
  (( ++count ))
  sleep 20
done > >(nc -q 192.168.100.161 2612)

echo "Ran $count loops before exiting" >&2

There, the redirection is done as a process substitution, and the loop takes place inside the same shell instance that continues after it exits. See BashFAQ #24 for more details on this problem and solution.

like image 97
Charles Duffy Avatar answered Oct 25 '25 18:10

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!