You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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.

Step 1: Choose a Lightweight Web Framework

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
Step 2: Write the Core Script

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)
Step 3: Test It Over Your LAN
  1. Find your computer's local IP address:

    • On Windows: Run ipconfig and look for "IPv4 Address" under your active network adapter.
    • On macOS/Linux: Run ifconfig or ip addr and find the inet value for your LAN interface (usually starts with 192.168.x.x or 10.x.x.x).
  2. Start the script:

    python your_script_name.py
    
  3. From another device on the same LAN, open a browser and visit:

    http://[your-computer-ip]:5000/execute-task?token=my_lan_secret_123
    

    You should see the success message, and your script will run the custom code you added.

Step 4: Keep the Script Running Long-Term

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.exe instead of python.exe to 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.
Important Notes
  • 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-files or /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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:03:45