#!/usr/bin/env python3 """ HTTP Output Server - Receives POST requests with JSON ping results Usage: python3 http_output_server.py """ from http.server import HTTPServer, BaseHTTPRequestHandler import json import signal import sys from datetime import datetime class OutputHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) print(f"\n{'='*60}") print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Received POST request") print(f"{'='*60}") try: data = json.loads(post_data) print(json.dumps(data, indent=2)) # Summary print(f"\nšŸ“Š Summary:") if isinstance(data, list): print(f" Total results: {len(data)}") for result in data: ip = result.get('ip', 'unknown') loss = result.get('packet_loss', 0) avg_rtt = result.get('avg_rtt', 0) error = result.get('error', '') traceroute = result.get('traceroute') if error: print(f" āŒ {ip}: ERROR - {error}") else: rtt_ms = avg_rtt / 1_000_000 # Convert ns to ms print(f" āœ… {ip}: {loss}% loss, avg RTT: {rtt_ms:.2f}ms") if traceroute: hops = traceroute.get('hops', []) method = traceroute.get('method', 'unknown') print(f" šŸ›¤ļø Traceroute ({method}): {len(hops)} hops") for hop in hops[:5]: # Show first 5 hops ttl = hop.get('ttl') hop_ip = hop.get('ip', '*') if hop.get('timeout'): print(f" {ttl}. * (timeout)") else: hop_rtt = hop.get('rtt', 0) / 1_000_000 print(f" {ttl}. {hop_ip} ({hop_rtt:.2f}ms)") if len(hops) > 5: print(f" ... and {len(hops) - 5} more hops") except json.JSONDecodeError: print("āš ļø Invalid JSON received") print(post_data.decode('utf-8', errors='replace')) print(f"{'='*60}\n") # Send response self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(b'{"status": "received"}') def log_message(self, format, *args): # Suppress default logging pass def signal_handler(sig, frame): print("\n\nšŸ›‘ Shutting down gracefully...") sys.exit(0) if __name__ == "__main__": PORT = 8081 # Register signal handlers for graceful shutdown signal.signal(signal.SIGINT, signal_handler) # Ctrl+C signal.signal(signal.SIGTERM, signal_handler) # kill command server = HTTPServer(('0.0.0.0', PORT), OutputHandler) print(f"šŸ“„ HTTP Output Server running on http://localhost:{PORT}") print(f" Waiting for POST requests with ping results...") print(f" Press Ctrl+C to stop") try: server.serve_forever() except KeyboardInterrupt: pass finally: server.server_close() print("\nāœ… Server stopped cleanly")