如何通过带密码保护的网页触发服务器端Python脚本控制PC开机?
解决方案:带密码保护的网页触发PC开机脚本
嘿,这个项目听起来超实用!我刚好有几个适合你的轻量方案,都能轻松实现带密码保护的触发按钮,还能稳稳在服务器端运行你的Arduino控制脚本,咱们一个个来看:
方案一:用Flask快速搭建(入门首选)
Flask是极简的Python Web框架,完全适配你的小场景,搭配HTTP Basic Auth就能快速实现密码保护,代码量少还容易调试。
步骤1:安装依赖
先装Flask和身份验证扩展:
pip install flask flask-httpauth
步骤2:编写核心代码
把下面的代码保存为power_controller.py,记得替换成你的用户名密码、Arduino脚本路径:
from flask import Flask, render_template_string from flask_httpauth import HTTPBasicAuth import subprocess import os app = Flask(__name__) auth = HTTPBasicAuth() # 推荐从环境变量读取密码,避免硬编码(更安全) USER_DATA = { os.getenv("PC_CONTROL_USER", "admin"): os.getenv("PC_CONTROL_PASS", "your_secure_password") } @auth.verify_password def verify_password(username, password): if username in USER_DATA and USER_DATA[username] == password: return username # 内嵌简单的网页模板,带触发按钮 HTML_TEMPLATE = """ <!DOCTYPE html> <html> <head> <title>PC 开机控制器</title> <style> body { font-family: Arial; max-width: 400px; margin: 2rem auto; text-align: center; } button { padding: 0.8rem 2rem; font-size: 1.2rem; background: #2196F3; color: white; border: none; border-radius: 4px; cursor: pointer; } button:hover { background: #1976D2; } </style> </head> <body> <h1>远程控制PC开机</h1> <form method="POST" action="/trigger-power"> <button type="submit">点击触发开机</button> </form> </body> </html> """ @app.route('/') @auth.login_required def index(): return render_template_string(HTML_TEMPLATE) @app.route('/trigger-power', methods=['POST']) @auth.login_required def trigger_power(): # 调用你的Arduino控制脚本 try: # 替换成你实际的脚本路径 subprocess.run(["python3", "/home/pi/control_arduino.py"], check=True) return "<h3>开机指令已成功发送!</h3><p><a href='/'>返回首页</a></p>" except subprocess.CalledProcessError as e: return f"<h3>执行出错:{str(e)}</h3><p><a href='/'>返回首页</a></p>", 500 if __name__ == '__main__': # 生产环境请关闭debug,绑定0.0.0.0让局域网内设备都能访问 app.run(host='0.0.0.0', port=5000, debug=False)
步骤3:运行服务
启动前可以先设置环境变量(可选,更安全):
export PC_CONTROL_USER="your_name" export PC_CONTROL_PASS="your_strong_password"
然后运行脚本:
python3 power_controller.py
现在在浏览器访问http://你的树莓派IP:5000,会弹出登录框,验证通过后就能看到触发按钮了!
方案二:用FastAPI(现代API首选)
如果你想同时支持网页触发和API调用,FastAPI是更好的选择——它自带API文档,性能也更优,同样支持简单的身份验证。
步骤1:安装依赖
pip install fastapi uvicorn python-multipart
步骤2:编写核心代码
保存为power_controller_fastapi.py:
from fastapi import FastAPI, HTTPException, Depends, Request from fastapi.security import HTTPBasic, HTTPBasicCredentials from fastapi.responses import HTMLResponse import subprocess import os app = FastAPI() security = HTTPBasic() USER_DATA = { os.getenv("PC_CONTROL_USER", "admin"): os.getenv("PC_CONTROL_PASS", "your_secure_password") } def verify_credentials(credentials: HTTPBasicCredentials = Depends(security)): if credentials.username not in USER_DATA or USER_DATA[credentials.username] != credentials.password: raise HTTPException(status_code=401, detail="用户名或密码错误") return credentials.username HTML_TEMPLATE = """ <!DOCTYPE html> <html> <head> <title>PC 开机控制器</title> <style> body { font-family: Arial; max-width: 400px; margin: 2rem auto; text-align: center; } button { padding: 0.8rem 2rem; font-size: 1.2rem; background: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; } button:hover { background: #388E3C; } </style> </head> <body> <h1>远程控制PC开机</h1> <form method="POST" action="/trigger-power"> <button type="submit">点击触发开机</button> </form> </body> </html> """ @app.get("/", response_class=HTMLResponse) async def root(credentials: HTTPBasicCredentials = Depends(verify_credentials)): return HTML_TEMPLATE @app.post("/trigger-power") async def trigger_power(credentials: HTTPBasicCredentials = Depends(verify_credentials)): try: subprocess.run(["python3", "/home/pi/control_arduino.py"], check=True) return {"message": "开机指令已成功发送"} except subprocess.CalledProcessError as e: raise HTTPException(status_code=500, detail=f"执行脚本出错: {str(e)}") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)
步骤3:运行服务
同样可以先设置环境变量,然后启动:
python3 power_controller_fastapi.py
访问http://你的树莓派IP:8000就能看到网页,访问http://你的树莓派IP:8000/docs还能看到自动生成的API文档,方便以后用其他设备调用接口。
关键注意事项
- 权限问题:确保运行Web服务的用户(比如pi)有权限访问Arduino串口,可以执行
sudo usermod -aG dialout pi,然后重启树莓派生效。 - 生产部署:如果长期使用,不要用自带的开发服务器,Flask可以搭配Gunicorn+Nginx,FastAPI搭配Uvicorn+Nginx,这样更稳定安全。
- 密码安全:绝对不要把密码硬编码在代码里,用环境变量或者配置文件存储更稳妥。
内容的提问来源于stack exchange,提问作者Nicolas Formichella
相关产品推荐
相关产品推荐

