diff --git a/MP1/client.py b/MP1/client.py index c37f832..8dac95a 100644 --- a/MP1/client.py +++ b/MP1/client.py @@ -16,19 +16,40 @@ ALL_IPS = [ ] def grep_all_ips(ips, cmd): - for ip in ips: + match_count = [] + + for i, ip in enumerate(ips): try: client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((ip, PORT)) - print(f"Connected to server at {ip}:{PORT}") + # print(f"Connected to server at {ip}:{PORT}") + + full_cmd = cmd + f" ./machine.{i + 1}.log" + + client_socket.sendall(full_cmd.encode()) + data = client_socket.recv(65536).decode() + + count = len(data.splitlines()) + match_count.append(count) + if count > 0: + print(f"Filename: machine.{i + 1}.log") + print(f"Matches: {count}") + print(data) - client_socket.sendall(cmd.encode()) - data = client_socket.recv(65536) - print("Received:", data.decode()) except Exception as e: print(f"Failed to connect to {ip}:{PORT} - {e}") finally: client_socket.close() + + return match_count -cmd = input("Enter the command to execute on all servers: ") -grep_all_ips(ALL_IPS, cmd) \ No newline at end of file +while True: + cmd = input(">> ").strip() + match_count = grep_all_ips(ALL_IPS, cmd) + + print("=========================== SUMMARY ===========================") + for i, count in enumerate(match_count): + if count > 0: + print(f"machine.{i + 1}.log: {count} matches") + print(f"Total matches: {sum(match_count)}") + print("===============================================================") \ No newline at end of file diff --git a/MP1/server.py b/MP1/server.py index c2a0c2e..19e2cf0 100644 --- a/MP1/server.py +++ b/MP1/server.py @@ -11,16 +11,27 @@ server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((HOST, PORT)) server_socket.listen() -# print(f"Server listening on {HOST}:{PORT}") +print(f"Server listening on {HOST}:{PORT}") while True: conn, addr = server_socket.accept() - # print(f"Connected by {addr}") + print(f"Connected by {addr}") command = conn.recv(65536) # print("Received Grep Command:", command.decode()) - result = subprocess.run(shlex.split(command.decode()), capture_output=True, text=True) + command_args = shlex.split(command.decode()) + + if not command_args or command_args[0] != "grep": + response = "Invalid command. Please use the 'grep' command." + conn.sendall(response.encode()) + conn.close() + continue + + command_args.insert(1, "-n") + + result = subprocess.run(command_args, capture_output=True, text=True) + conn.sendall(result.stdout.encode()) conn.close()