Untitled
# -*- coding: utf-8 -*- import json import os from flask import Flask, render_template, request, jsonify from wakeonlan import send_magic_packet import subprocess import platform app = Flask(__name__) # Initialize saved PCs pcs_file = "pcs.json" def load_pcs(): """Load the list of registered PCs from pcs.json, handling errors.""" if os.path.exists(pcs_file): try: with open(pcs_file, "r") as file: return json.load(file) except json.JSONDecodeError: print("[ERROR] Corrupted pcs.json file. Resetting...") with open(pcs_file, "w") as file: json.dump([], file) return [] pcs = load_pcs() def save_pcs(): """Save the list of registered PCs to pcs.json.""" with open(pcs_file, "w") as file: json.dump(pcs, file, indent=4) def ping_device(ip): """Check if a device is reachable via ping.""" param = "-n" if platform.system().lower() == "windows" else "-c" command = ["ping", param, "1", ip] try: subprocess.check_output(command, stderr=subprocess.STDOUT, universal_newlines=True) return True except subprocess.CalledProcessError: return False def determine_status(ip, mac): """Determine the status of a device using ping.""" try: ping = ping_device(ip) print(f"[DEBUG] IP: {ip}, MAC: {mac}, Ping: {ping}") return "Online" if ping else "Offline" except Exception as e: print(f"[ERROR] Status check failed for {ip} ({mac}): {e}") return "Undefined" @app.route("/") def home(): """Render the main page.""" return render_template("index.html") @app.route("/api/pcs", methods=["GET"]) def get_pcs(): """Return the current list of saved PCs.""" for pc in pcs: pc["status"] = determine_status(pc["ip"], pc["mac"]) return jsonify({"saved": pcs}) @app.route("/add", methods=["POST"]) def add_pc(): """Add a device to the list of saved PCs.""" name = request.form["name"] device_data = request.form["device"] ip, mac = device_data.split("|") pcs.append({"name": name, "ip": ip, "mac": mac, "status": "Offline"}) save_pcs() return jsonify({"success": True}) @app.route("/wake", methods=["POST"]) def wake_pc(): """Send a Wake-on-LAN packet to a device.""" mac = request.form["mac"] try: send_magic_packet(mac) return jsonify({"success": True, "message": f"Wake-on-LAN packet sent to {mac}."}) except Exception as e: return jsonify({"success": False, "error": str(e)}) @app.route("/delete", methods=["POST"]) def delete_pc(): """Remove a device from the list of saved PCs.""" name = request.form["name"] global pcs pcs = [pc for pc in pcs if pc["name"] != name] save_pcs() return jsonify({"success": True}) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000, debug=True)
Leave a Comment