Untitled
unknown
plain_text
10 months ago
5.0 kB
5
Indexable
# -*- 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
import os
import psutil # Für CPU, Speicher usw.
app = Flask(__name__)
# Initialize saved PCs
try:
with open("pcs.json", "r") as file:
pcs = json.load(file)
except FileNotFoundError:
pcs = []
# Function to save PCs
def save_pcs():
with open("pcs.json", "w") as file:
json.dump(pcs, file, indent=4)
# Function to ping a device
def ping_device(ip):
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
# Function to scan the network
def scan_network():
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
# Function to determine device status
def determine_status(pc):
ip = pc["ip"]
online = ping_device(ip)
if online:
if "last_online" not in pc or pc["status"] == "Offline":
pc["last_online"] = datetime.now().isoformat()
pc["status"] = "Online"
else:
pc["status"] = "Offline"
pc["last_online"] = None
return pc["status"]
# Function to calculate uptime
def calculate_uptime(pc):
if pc["status"] == "Online" and "last_online" in pc and pc["last_online"]:
last_online = datetime.fromisoformat(pc["last_online"])
uptime = datetime.now() - last_online
return str(uptime).split(".")[0] # Remove microseconds
return "N/A"
# Function to send shutdown
def send_shutdown(ip, restart=False):
action = "reboot" if restart else "shutdown"
command = f"net rpc {action} -I {ip} -U RemoteUser%Hyperlink123!"
try:
print(f"Executing command: {command}")
result = os.system(command)
print(f"Command result: {result}")
return result == 0
except Exception as e:
print(f"[ERROR] {action.capitalize()} failed for {ip}: {e}")
return False
@app.route("/")
def home():
return render_template("index.html")
@app.route("/api/pcs", methods=["GET"])
def get_pcs():
for pc in pcs:
determine_status(pc)
pc["uptime"] = calculate_uptime(pc)
return jsonify({"saved": pcs, "available": scan_network()})
@app.route("/add", methods=["POST"])
def add_pc():
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", "uptime": "N/A"})
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():
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("/shutdown", methods=["POST"])
def shutdown_pc():
try:
name = request.form["name"]
pc = next((pc for pc in pcs if pc["name"] == name), None)
if not pc:
return jsonify({"success": False, "error": f"Device '{name}' not found!"})
success = send_shutdown(pc["ip"])
if success:
return jsonify({"success": True, "message": f"Shutdown command sent to {name}."})
else:
return jsonify({"success": False, "error": f"Failed to shutdown {name}."})
except Exception as e:
return jsonify({"success": False, "error": str(e)})
@app.route("/api/system-info", methods=["GET"])
def system_info():
cpu = psutil.cpu_percent(interval=0.5)
memory = psutil.virtual_memory().percent
temperature = get_temperature()
return jsonify({"cpu": cpu, "memory": memory, "temperature": temperature})
def get_temperature():
try:
temp_output = subprocess.check_output(["vcgencmd", "measure_temp"]).decode("utf-8")
temp = temp_output.split("=")[1].split("'")[0]
return float(temp)
except Exception as e:
print(f"[ERROR] Could not read temperature: {e}")
return "N/A"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)Editor is loading...
Leave a Comment