How to read stdin in python?

Asked

Viewed 1,094 times

9

Using the netcat to monitor a particular 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, as for example, makes a chat system with sockets. My question is, with replicate the same behavior of "iterativity" in python?

With what I’ve been able to develop so far, I can receive the data and check it, but I’m still not able to send something back (using stdin, I suppose that’s the way to 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()

Thanks.

1 answer

5


Solved. In order for me to be able to replicate the behavior that 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 a "ok" if you receive the data waiting at the door.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.