如何通过带密码验证的网页触发服务器端Python脚本控制PC开机?
Hey there! You’re already ahead of the game with your Arduino control script sorted—let’s focus on bridging that to a password-protected web button that triggers your server-side code. CherryPy does feel overkill for this simple use case, so let’s go with Flask (super Python-friendly, minimal, and perfect for small projects like this).
方案一:Flask + HTTP Basic Auth(快速实现)
This is the simplest way to add password protection and link your web button to the Arduino script.
Step 1: Install Required Tools
First, set up the dependencies on your Raspberry Pi:
pip install flask flask-httpauth
Step 2: Write the Flask App
Create a file named remote_power.py with this code (adjust paths and credentials to match your setup):
from flask import Flask, render_template_string from flask_httpauth import HTTPBasicAuth import subprocess app = Flask(__name__) auth = HTTPBasicAuth() # Replace these with your own secure username and password USER_CREDENTIALS = { "admin": "your_strong_password_here" } @auth.verify_password def check_credentials(username, password): if username in USER_CREDENTIALS and USER_CREDENTIALS[username] == password: return username # Wrap your existing Arduino control logic here def trigger_pc_power(): # Replace this line with the path to your working Arduino script subprocess.run(["python3", "/home/pi/your_arduino_script.py"]) return "PC power trigger sent successfully!" @app.route('/') @auth.login_required def control_page(): # Simple HTML interface with a trigger button return render_template_string(''' <h1>Remote PC Power Controller</h1> <form method="POST" action="/trigger"> <button style="padding: 10px 20px; font-size: 16px;" type="submit">Turn On PC</button> </form> ''') @app.route('/trigger', methods=['POST']) @auth.login_required def handle_trigger(): result = trigger_pc_power() return f"<h2>{result}</h2><p><a href='/'>Go back to control page</a></p>" if __name__ == '__main__': # Run the server on all network interfaces (port 5000) app.run(host='0.0.0.0', port=5000, debug=False)
Step 3: Test the Setup
- Update
/home/pi/your_arduino_script.pyto the actual path of your existing Arduino control code. - Set a strong username and password in
USER_CREDENTIALS. - Start the service:
python3 remote_power.py
- Visit
http://[your-raspi-ip]:5000from any device on your network—you’ll get a browser login prompt, then can click the button to trigger your Arduino script.
方案二:表单式密码验证(更用户友好)
If you prefer a web form for password entry instead of the browser’s basic auth prompt, tweak the Flask app like this:
from flask import Flask, render_template_string, request, redirect, url_for import subprocess app = Flask(__name__) # Replace with your secure password SECURE_PASSWORD = "your_strong_password_here" def trigger_pc_power(): subprocess.run(["python3", "/home/pi/your_arduino_script.py"]) return "PC power trigger sent!" @app.route('/', methods=['GET', 'POST']) def login_page(): if request.method == 'POST': entered_pass = request.form.get('password') if entered_pass == SECURE_PASSWORD: return redirect(url_for('trigger_page')) else: return "<h2>Incorrect password!</h2><a href='/'>Try again</a>" # Login form interface return render_template_string(''' <h1>Remote PC Power Control</h1> <form method="POST"> <label for="password">Enter Access Password:</label> <input type="password" id="password" name="password" required> <button type="submit">Continue</button> </form> ''') @app.route('/trigger') def trigger_page(): result = trigger_pc_power() return f"<h2>{result}</h2><p><a href='/'>Go back to login</a></p>" if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=False)
部署提示:让服务持久运行
To keep the Flask app running even after you close the terminal or restart the Pi:
- Create a systemd service file:
sudo nano /etc/systemd/system/remote-power.service
- Paste this content (adjust paths to match your setup):
[Unit] Description=Remote PC Power Control Service After=multi-user.target [Service] User=pi ExecStart=/usr/bin/python3 /home/pi/remote_power.py Restart=always [Install] WantedBy=multi-user.target
- Enable and start the service:
sudo systemctl daemon-reload sudo systemctl enable remote-power.service sudo systemctl start remote-power.service
安全 Tips
- Use HTTPS: If you plan to access this outside your home network, set up HTTPS with a free Let’s Encrypt certificate to encrypt password traffic.
- Restrict IP Access: Add firewall rules to only allow connections from your local network or trusted IPs.
- Avoid Weak Passwords: This is non-negotiable for remote access—use a long, unique password.
替代选项:FastAPI(现代异步框架)
If you want a more modern, async-capable solution, FastAPI works great too. It has built-in support for OAuth2 password flows if you need more advanced authentication down the line.
内容的提问来源于stack exchange,提问作者Nicolas Formichella

