Reputation: 1
I want to create a script that uses a couple arguments from the TCP output and prints something back to the TCP input.
I'm trying to solve this with bash, I tried:
exec 3<>/dev/tcp/url/port;
msg=$(head -2 <&3)
arg1=$( some grep and sed operation on msg) #is a number
arg2=$( some grep and sed operation on msg) #is a string
counter=0
while [ $counter -lt $arg1 ]
do
#here I want to print something to netcat input
echo "$arg2 sometext" >&3;
((counter++))
done
#then print the awnser from the server
cat <&3
But the script can't write back to netcat input. (No error, ist just does nothing after echo "$arg2 sometext" >&3
)
Upvotes: 0
Views: 241
Reputation: 295530
Fewer headaches if you avoid /dev/tcp
and use socat
to run your code with stdin and stdout connected to the socket.
myfunc() {
local msg msg1 msg2 arg1 arg2 counter
IFS= read -r msg1 # first line of msg
IFS= read -r msg2 # second line of msg
msg="$msg1"$'\n'"$msg2"
# FYI: There are usually better ways to do string manipulation in bash than grep/sed/etc
arg1=$(do-something-with "$msg" </dev/null)
arg2=$(do-something-with "$msg" </dev/null)
for (( counter=0; counter<arg1; counter++ )); do
echo "$arg2 sometext"
done
cat >&2 # write to stderr, since anything to stdout will go to the remote socket
}
export -f myfunc
socat TCP:"$host":"$port" "SYSTEM:bash -xc myfunc"
Upvotes: 1