基于Python搭建常驻HTTP服务远程触发代码执行的技术咨询
Hey there! Building a long-running Python script that triggers actions via HTTP requests on your local network is totally doable—let's break this down step by step with a simple, practical implementation.
For this use case, Flask is perfect—it's minimal, easy to set up, and more than enough to handle basic HTTP triggers. If you prefer something with async support later, you could switch to FastAPI, but Flask will get you up and running in minutes.
First, install Flask via pip:
pip install flask
Here's a complete example that creates a web endpoint, validates requests, and runs your custom code when triggered:
from flask import Flask, request # Initialize the Flask app app = Flask(__name__) # Set a secret token to prevent unauthorized access (replace with your own secure string) VALID_TOKEN = "my_lan_secret_123" # Define your HTTP endpoint - this is what you'll hit in the browser @app.route('/execute-task', methods=['GET']) def execute_task(): # First, verify the request is authorized incoming_token = request.args.get('token') if incoming_token != VALID_TOKEN: return "❌ Unauthorized - invalid token", 401 # -------------------------- # Your custom code goes here # -------------------------- print("🔧 Running your specified operation...") # Example: Run a function, process a file, control hardware, etc. operation_result = "✅ Custom operation completed successfully!" # Return a response to confirm it worked return operation_result if __name__ == '__main__': # Run the server on 0.0.0.0 (allows access from any device on the LAN) # Use a port of your choice (5000 is default, but pick any unused port) app.run(host='0.0.0.0', port=5000, debug=False)
Find your computer's local IP address:
- On Windows: Run
ipconfigand look for "IPv4 Address" under your active network adapter. - On macOS/Linux: Run
ifconfigorip addrand find theinetvalue for your LAN interface (usually starts with 192.168.x.x or 10.x.x.x).
- On Windows: Run
Start the script:
python your_script_name.pyFrom another device on the same LAN, open a browser and visit:
http://[your-computer-ip]:5000/execute-task?token=my_lan_secret_123You should see the success message, and your script will run the custom code you added.
You don't want to keep a terminal window open forever—here's how to make the script run persistently:
On Linux/macOS:
Use nohup to run the script in the background, even after you close the terminal:
nohup python your_script_name.py > script_logs.out 2>&1 &
Logs will be saved to script_logs.out if you need to debug later.
On Windows:
- Use
pythonw.exeinstead ofpython.exeto run the script without a terminal window:pythonw.exe your_script_name.py - To make it start automatically when your computer boots, create a batch file with the above command, then add it to Windows Task Scheduler as a startup task.
- Firewall Settings: Make sure your computer's firewall allows incoming connections on the port you chose (5000 in the example). You may need to add an exception for Python or the specific port.
- Security: The token validation is basic but essential—never expose an unprotected endpoint on your network, as anyone could trigger it. For extra security, you could use HTTP Basic Auth instead of a token.
- Extendability: Want multiple commands? Add more routes (like
/backup-filesor/start-service) and link each to its own code block. You can also use POST requests if you need to send more data to the script.
内容的提问来源于stack exchange,提问作者Zdog16

