I'm doing a server client with sockets, and I'd like to run a command from the client to the server (where it runs), save the output, and then send it (python 2.7.15)
Server Code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#Se importa el módulo
import socket, os, getpass, shutil
from subprocess import PIPE, Popen
name_host_server = getpass.getuser()
carpeta_actual_server = os.getcwd()
#instanciamos un objeto para trabajar con el socket
ser = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = ""
port = 8000
#Puerto y servidor que debe escuchar
ser.bind((server, port))
ser.listen(1)
#Instanciamos un objeto cli (socket cliente) para recibir datos
cli, addr = ser.accept()
while True:
recibido = cli.recv(1024)
if recibido=="close":
break
comando = recibido.split(" ", 1)
proceso = Popen(comando, stdout=PIPE, stderr=PIPE)
resultado = proceso.stdout.read()
error_resultado = proceso.stderr.read()
if resultado:
cli.send(resultado)
elif error_resultado:
cli.send(error_resultado)
proceso.stdout.close()
if ser == True:
print("Conexion cerrada")
#Cerramos la instancia del socket cliente y servidor
cli.close()
ser.close()
I've been reporting and it can be done with the subprocess module, it's easy to understand, but it does not work at all well.
Here's the problem:
while True:
recibido = cli.recv(1024)
if recibido=="close":
break
comando = recibido.split(" ", 1)
proceso = Popen(comando, stdout=PIPE, stderr=PIPE)
resultado = proceso.stdout.read()
error_resultado = proceso.stderr.read()
if resultado:
cli.send(resultado)
elif error_resultado:
cli.send(error_resultado)
proceso.stdout.close()
What I do is a variable comando
that catches me the text string that I put, and separates it into a list with split()
, separates it in the first space there is. Then I do the variable proceso
where I execute the command, and I capture what is in the pipes stdout=PIPE
and stderr=PIPE
.
I read the output of the command in the variable resultado
and the error output in error_resultado
, to do an if by which I say that if the resultado
or resultado_error
comes out, send me the output to the customer.
All that goes well, but there are commands that do not quite go like cd
shred -u
, rm -r
, when I insert these commands, I get to see the argument --help
, since it gives error , which I do not understand.
The thing is that I do not understand its logic, since at the beginning of everything I do is convert the string into a list. that is, I do this:
>>> comando = "shred -u"
>>> resultado = comando.split(" ",1)
>>> print(resultado)
['shred', '-u']
Thing that should work because the subprocess module accepts the list (theoretically).