Programming Netcat TCP with Bash

I am trying to do some basic communication with a TCP client using strictly bash scripting. I have netcat at my disposal, and so I wrote this loop so far:

nc 10.0.0.104 4646 | while read line
do
   if [ "$line" == '{"cmd": 1}' ]
   then
      # Send text back to the TCP server
      echo '{"error": 0}'
   fi
done

The script can successfully connect to the server application you are using, but it's hard for me to figure out how to send text back to the netcat process.

+4
source share
1 answer

With Bash ≥4 you can use coproc:

#!/bin/bash

coproc nc { nc 10.0.0.104 4646; }

while [[ $nc_PID ]] && IFS= read -r -u${nc[0]} line; do
    case $line in
        ('{"cmd": 1}')
            printf >&${nc[1]} '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done

This avoids the use of temporary fixes. Without coproc, I think, the only option is to use fifos explicitly. Here is an example:

#!/bin/bash

mkfifo fifo_in

while IFS= read -r line; do
    case $line in
        ('{"cmd": 1}')
            printf '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done < <(nc 10.0.0.104 4646 < fifo_in) > fifo_in

fifo: mktemp, fifo, trap script, .


/dev/tcp

Bash , nc, :

#!/bin/bash

# open TCP connection, available on file descriptor 3
exec 3<> /dev/tcp/10.0.0.104/4646 || exit

while IFS= read -r -u3 line; do
    case $line in
        ('{"cmd": 1}')
            printf >&3 '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done

!

+3

Source: https://habr.com/ru/post/1568531/


All Articles