96 lines
2.3 KiB
Python
96 lines
2.3 KiB
Python
from flask import Flask, send_from_directory, request, jsonify, Response
|
|
import subprocess
|
|
import base64
|
|
import ping3
|
|
import os
|
|
|
|
app = Flask(__name__, static_folder=".")
|
|
|
|
PC_MAC = "58:11:22:d6:9d:8d"
|
|
PC_IP = "192.168.1.4"
|
|
SSH_USER = "sarthak"
|
|
|
|
AUTH_USER = "admin"
|
|
AUTH_PASS = "12345"
|
|
|
|
def check_auth(auth_header):
|
|
if not auth_header or not auth_header.startswith("Basic "):
|
|
return False
|
|
|
|
encoded = auth_header.split(" ")[1]
|
|
decoded = base64.b64decode(encoded).decode("utf-8")
|
|
user, pwd = decoded.split(":", 1)
|
|
|
|
return user == AUTH_USER and pwd == AUTH_PASS
|
|
|
|
def require_auth():
|
|
return Response(
|
|
"Authentication Required",
|
|
401,
|
|
{"WWW-Authenticate": 'Basic realm="Restricted"'}
|
|
)
|
|
|
|
@app.route("/")
|
|
def index():
|
|
return send_from_directory(".", "index.html")
|
|
|
|
@app.route("/down")
|
|
def down():
|
|
return send_from_directory(".", "down.html")
|
|
|
|
@app.route("/wol")
|
|
def wol_page():
|
|
# auth = request.headers.get("Authorization")
|
|
# if not check_auth(auth):
|
|
# return require_auth()
|
|
return send_from_directory(".", "wol.html")
|
|
|
|
|
|
@app.route("/api/status")
|
|
def api_status():
|
|
# auth = request.headers.get("Authorization")
|
|
# if not check_auth(auth):
|
|
# return require_auth()
|
|
|
|
try:
|
|
alive = ping3.ping(PC_IP, timeout=1) is not None
|
|
except:
|
|
alive = False
|
|
|
|
return jsonify({ "online": alive })
|
|
|
|
|
|
@app.route("/api/wake", methods=["POST"])
|
|
def api_wake():
|
|
# auth = request.headers.get("Authorization")
|
|
# if not check_auth(auth):
|
|
# return require_auth()
|
|
|
|
try:
|
|
subprocess.run(["wakeonlan", PC_MAC])
|
|
return jsonify({ "success": True })
|
|
except Exception as e:
|
|
return jsonify({ "success": False, "error": str(e) })
|
|
|
|
|
|
@app.route("/api/shutdown", methods=["POST"])
|
|
def api_shutdown():
|
|
# auth = request.headers.get("Authorization")
|
|
# if not check_auth(auth):
|
|
# return require_auth()
|
|
|
|
ssh_cmd = [
|
|
"ssh",
|
|
f"{SSH_USER}@{PC_IP}",
|
|
"shutdown -h now"
|
|
]
|
|
|
|
try:
|
|
subprocess.Popen(ssh_cmd)
|
|
return jsonify({"success": True})
|
|
except Exception as e:
|
|
return jsonify({"success": False, "error": str(e)})
|
|
|
|
if __name__ == "__main__":
|
|
print("Server running at http://0.0.0.0:5000/wol")
|
|
app.run(host="0.0.0.0", port=5000)
|