Servidor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import socket import subprocess def start_server(host='0.0.0.0', port=12345): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket: server_socket.bind((host, port)) server_socket.listen() print(f'Server listening on {host}:{port}') while True: client_socket, addr = server_socket.accept() with client_socket: print(f'Connected by {addr}') while True: command = client_socket.recv(1024).decode('utf-8') if not command: break print(f'Received command: {command}') result = subprocess.run(command, shell=True, capture_output=True, text=True) client_socket.sendall(result.stdout.encode('utf-8') + result.stderr.encode('utf-8')) print(f'Sent result to {addr}') if __name__ == '__main__': start_server() |
Cliente
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import socket def send_command(host='127.0.0.1', port=12345, command=''): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket: client_socket.connect((host, port)) client_socket.sendall(command.encode('utf-8')) data = client_socket.recv(4096).decode('utf-8') print('Received result:') print(data) if __name__ == '__main__': host = input('Enter server IP: ') port = int(input('Enter server port: ')) while True: command = input('Enter command to execute (or "exit" to quit): ') if command.lower() == 'exit': break send_command(host, port, command) |