Untitled
# -*- coding: utf-8 -*- import json from flask import Flask, render_template, request, jsonify from wakeonlan import send_magic_packet import subprocess import platform from datetime import datetime app = Flask(__name__) # Initialize saved PCs try: with open("pcs.json", "r") as file: pcs = json.load(file) except FileNotFoundError: pcs = [] def save_pcs(): """Save the list of registered PCs to pcs.json.""" with open("pcs.json", "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 scan_network(): """Scan the local network for devices.""" devices = [] try: result = subprocess.run(['sudo', 'arp-scan', '--localnet'], stdout=subprocess.PIPE, text=True) for line in result.stdout.split("\n"): if "192.168." in line: parts = line.split() if len(parts) >= 3: ip = parts[0] mac = parts[1] name = parts[2] if len(parts) > 2 else "Unknown" devices.append({"ip": ip, "mac": mac, "name": name}) except Exception as e: print(f"[ERROR] Network scan failed: {e}") return devices def determine_status(ip, mac): """Determine the status of a device using ping.""" try: ping = ping_device(ip) 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 and available network devices.""" for pc in pcs: pc["status"] = determine_status(pc["ip"], pc["mac"]) return jsonify({"saved": pcs, "available": scan_network()}) @app.route("/add", methods=["POST"]) def add_pc(): """Add a device to the list of saved PCs.""" try: 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, "message": f"Device '{name}' added successfully!"}) except Exception as e: return jsonify({"success": False, "error": str(e)}) @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.""" try: name = request.form["name"] global pcs pcs = [pc for pc in pcs if pc["name"] != name] save_pcs() return jsonify({"success": True, "message": f"Device '{name}' removed successfully!"}) except Exception as e: return jsonify({"success": False, "error": str(e)}) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000, debug=True)
Leave a Comment