Untitled
unknown
plain_text
10 months ago
3.9 kB
4
Indexable
# -*- 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"
def scan_network():
"""Scan the local network for devices."""
devices = []
try:
result = subprocess.run(['sudo', 'arp-scan', '--localnet'], stdout=subprocess.PIPE, text=True)
print("[DEBUG] arp-scan output:\n", result.stdout) # Debugging
for line in result.stdout.split("\n"):
if "192.168." in line: # Filter lines containing IP addresses
parts = line.split()
if len(parts) >= 2:
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
@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."""
print("[DEBUG] Loading saved PCs...")
for pc in pcs:
pc["status"] = determine_status(pc["ip"], pc["mac"])
print("[DEBUG] Saved PCs:", pcs)
devices = scan_network()
print("[DEBUG] Available devices:", devices)
return jsonify({"saved": pcs, "available": devices})
@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)Editor is loading...
Leave a Comment