How to read stdin in python?

7
Using netcat to monitor a certain port on my device using the shell command terminal, I can check the data received by it and send data back to the connected device, such as a chat system with sockets. My question is, with replicating the same "iterativity" behavior in python?

With what I've been able to develop so far, I can get the data and check it, but I'm still not able to send something back (using stdin , which I suppose is the way to do it).

from threading import Thread
import os
import time
import subprocess

class netcat(Thread):
    def __init__(self):

        Thread.__init__(self)

        self.cmd  = ['sudo nc -l -p 12']
        self.proc = subprocess.Popen(self.cmd, shell = True,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE,
                                     stdin=subprocess.PIPE)

        self.output = self.proc.stdout.read().decode('utf-8')
        self.error  = self.proc.stderr.read().decode('utf-8')
        #self.intput = self.proc.stdin.write("y\r")

    def run(self):

        while True:

            time.sleep(1)

            print("out: " + self.output)
            print("err: " + self.error )
            #print("in : " + self.input )

            if self.output == 'send':
                self.proc.stdin.write("ok")
nc = netcat()
nc.start()

Thank you.

    
asked by anonymous 31.10.2018 / 14:12

1 answer

3

Solved. So that I was able to replicate the behavior I got using the shell and be able to both read and respond to what was written on the port, I had to access it through two different processes. In order to be able to prove and serve others, I have developed a test code that responds with "ok" if you receive the data you are waiting for at the port.

import subprocess    

cmd  = ['sudo nc -l -p 2000']

while True:

    proc = subprocess.Popen(cmd, shell = True, stdout=subprocess.PIPE)
    out  = proc.stdout.read().decode('utf-8')    

    if out == 'enviado':        

        while True:
            proc = subprocess.Popen(cmd, shell = True, stdin=subprocess.PIPE)
            proc.stdin.write(b'ok')
            proc.stdin.flush()
            proc.stdin.close()            
            break
    
15.11.2018 / 13:42