From fd117847448ae34a1e70949081181c010ea4c620 Mon Sep 17 00:00:00 2001 From: Aryan Singh Date: Sun, 13 Sep 2026 16:06:07 -0500 Subject: [PATCH] using shlex on the client --- MP1/client.py | 10 +++++----- MP1/server.py | 37 ++++++++++++++++++------------------- 2 files changed, 23 insertions(+), 24 deletions(-) diff --git a/MP1/client.py b/MP1/client.py index 3f3298e..0f12fc3 100644 --- a/MP1/client.py +++ b/MP1/client.py @@ -2,6 +2,7 @@ import socket import sys import time +import shlex PORT = 5056 ALL_IPS = [ @@ -49,10 +50,9 @@ def grep_all_ips(ips, cmd, if_unit_test): client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((ip, PORT)) - if if_unit_test: - full_cmd = cmd + f" ./machine.{i + 1}.test.log" - else: - full_cmd = cmd + f" ./machine.{i + 1}.log" + filename = f"machine.{i + 1}.test.log" if if_unit_test else f"machine.{i + 1}.log" + + full_cmd = shlex.join(cmd + [filename]) send_message(client_socket, full_cmd) data = receive_message(client_socket) @@ -74,7 +74,7 @@ def grep_all_ips(ips, cmd, if_unit_test): #main #if unit test flag exists, then use the test log files instead of the actual log files -cmd = "grep " + " ".join([arg for arg in sys.argv[1:] if arg != "-t"]) +cmd = ["grep ", *[arg for arg in sys.argv[1:] if arg != "-t"]] #track time start_time = time.perf_counter() match_count = grep_all_ips(ALL_IPS, cmd, if_unit_test=[x for x in sys.argv].count("-t") > 0) diff --git a/MP1/server.py b/MP1/server.py index aee259e..7810f75 100644 --- a/MP1/server.py +++ b/MP1/server.py @@ -44,25 +44,24 @@ while True: conn, addr = server_socket.accept() print(f"Connected by {addr}") - command = receive_message(conn) - if command is None: + try: + command = receive_message(conn) + if command is None: + conn.close() + continue + + command_args = shlex.split(command) + + command_args.insert(1, "-n") + + result = subprocess.run(command_args, cwd=SCRIPT_DIR, capture_output=True, text=True) + + send_message(conn, result.stdout + result.stderr) + + except Exception as e: + error_message = f"Error executing command: {e}" + send_message(conn, error_message) + finally: conn.close() - continue - - command_args = shlex.split(command) - - if not command_args or command_args[0] != "grep": - response = "Invalid command. Please use the 'grep' command." - send_message(conn, response) - conn.close() - continue - - command_args.insert(1, "-n") - - result = subprocess.run(command_args, cwd=SCRIPT_DIR, capture_output=True, text=True) - - send_message(conn, result.stdout + result.stderr) - - conn.close() server_socket.close()