Paku
Paku

Reputation: 797

Reading multiple times from netcat /w named pipe

I have a netcat listener, which responds to "ping" with a SHA1 hash:

$ nc localhost 1234 
ping
da4b9237bacccdf19c0760cab7aec4a8359010b0

And I'm trying to send this via a bash script

#!/usr/bin/env bash
set -euxo pipefail

cd /tmp
rm f || true
mkfifo f
echo ping > f & nc localhost 1234 < f | while read line; do
    echo $line | sha256sum - | awk '{print $2}' > f
done

This outputs:

./bashsender.sh    
+ cd /tmp
+ rm f
+ mkfifo f
+ echo ping
+ nc localhost 1234
+ read line
(process stays alive & blocks)

I am trying to achieve:

./bashsender.sh    
+ cd /tmp
+ rm f
+ mkfifo f
+ echo ping
+ nc localhost 1234
da4b9237bacccdf19c0760cab7aec4a8359010b0
+ read line
+ echo "da4b9237bacccdf19c0760cab7aec4a8359010b0"
+ sha256sum -
+ awk '{print $2}'
+ read line
a3db5c13ff90a36963278c6a39e4ee3c22e2a436
+ echo "a3db5c13ff90a36963278c6a39e4ee3c22e2a436"
+ sha256sum -
+ awk '{print $2}'
 

Any insight to what's going on and how to overcome this would be thoroughly appreciated! :)

Listener code:

import nclib
import hashlib
import binascii

nc = nclib.Netcat(listen=('localhost', 1234))
inputvar=nc.recv()
integervar=2
if(inputvar.decode("utf-8")=="ping"+"\n"):
    nc.send(hashlib.sha1(str(integervar).encode("utf-8")).hexdigest())
else:
    nc.send("WRONG")
    exit()
while True:
    integervar=integervar+1
    inputvar = nc.recv()
    if(inputvar.decode("utf-8")==(hashlib.sha256((hashlib.sha1(str(integervar-1).encode("utf-8")).hexdigest()+"\n").encode("utf-8")).hexdigest()+"\n")):
        nc.send("==="+hashlib.sha1(str(integervar).encode("utf-8")).hexdigest()+"===")
    else:
        nc.send("WRONG")
        exit()
    nc.send(hashlib.sha1(str(integervar).encode("utf-8")).hexdigest().encode("utf-8"))

Upvotes: 0

Views: 270

Answers (0)

Related Questions