You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何在Nginx服务器上通过GET/POST请求执行脚本?

Yes, You Absolutely Can Do This!

Great news—since you already have a secure public Nginx server on your Raspberry Pi, setting up a webhook to trigger a Python script is totally feasible. Let’s break down the process into actionable, easy-to-follow steps:

1. Build a Webhook Listener with Python

First, you’ll need a lightweight web service to catch incoming webhook requests and kick off your .py script. Flask is perfect for this—it’s lightweight enough for the Pi and dead simple to set up:

  • Install Flask if you haven’t already:

    pip install flask
    
  • Create a file webhook_server.py with this core setup (we’ll add critical security checks too):

    from flask import Flask, request, abort
    import subprocess
    import os
    import hmac
    import hashlib
    
    app = Flask(__name__)
    # Replace this with a strong, unique secret (keep this private!)
    WEBHOOK_SECRET = "your_ultra_secure_secret_here"
    
    def verify_webhook_signature(request):
        # This checks that the request comes from your trusted provider (e.g., GitHub/GitLab)
        # Example for GitHub: validate the X-Hub-Signature-256 header
        signature_header = request.headers.get('X-Hub-Signature-256')
        if not signature_header:
            abort(403)
        
        sha_name, signature = signature_header.split('=')
        if sha_name != 'sha256':
            abort(403)
        
        # Compute HMAC of the request body
        mac = hmac.new(WEBHOOK_SECRET.encode(), msg=request.data, digestmod=hashlib.sha256)
        if not hmac.compare_digest(mac.hexdigest(), signature):
            abort(403)
    
    @app.route('/webhook', methods=['POST'])
    def handle_webhook():
        # First, make sure the request is legitimate
        verify_webhook_signature(request)
    
        # Trigger your target Python script (use absolute paths to avoid confusion)
        target_script = "/home/pi/your_script.py"
        if os.path.exists(target_script):
            # Run the script in the background so we don't hang the webhook response
            subprocess.Popen(["python3", target_script])
            return "Script triggered successfully!", 200
        else:
            return "Target script not found!", 404
    
    if __name__ == '__main__':
        # Run the server locally—we'll proxy through Nginx next
        app.run(host='127.0.0.1', port=5000)
    

    Critical Note: Don’t skip the signature verification! This stops random strangers from triggering your script. Every legitimate webhook provider lets you set a secret to sign requests—match that secret here.

2. Configure Nginx to Proxy Webhook Requests

Since your Nginx server is already handling public traffic, add a location block to forward webhook requests to your Flask service. Edit your Nginx site config (usually in /etc/nginx/sites-available/your-site.conf):

server {
    # Your existing SSL/server config goes here

    location /webhook {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Test the config and reload Nginx to apply changes:

sudo nginx -t
sudo systemctl reload nginx

3. Fix Permissions & Dependencies

Make sure the user running your webhook server (or Nginx, if you opt to run it as www-data) has permission to execute your script and access its resources:

  • Set executable permissions on your target script:

    chmod +x /home/pi/your_script.py
    sudo chown pi:pi /home/pi/your_script.py  # Use www-data instead if running the service as that user
    
  • Install any dependencies your script needs for the correct user. For example, if your script uses requests:

    pip3 install requests  # Or sudo -u www-data pip3 install requests if running as www-data
    

4. Run the Webhook Server as a Background Service

You don’t want to keep a terminal open to run the Flask server—use systemd to manage it as a persistent service:

  • Create a service file at /etc/systemd/system/webhook.service:

    [Unit]
    Description=Webhook Server for Raspberry Pi Python Script
    After=network.target
    
    [Service]
    User=pi
    WorkingDirectory=/home/pi
    ExecStart=/usr/bin/python3 /home/pi/webhook_server.py
    Restart=always  # Auto-restart if the service crashes
    
    [Install]
    WantedBy=multi-user.target
    
  • Enable and start the service:

    sudo systemctl daemon-reload
    sudo systemctl enable webhook.service
    sudo systemctl start webhook.service
    
  • Check if it’s running properly:

    sudo systemctl status webhook.service
    

5. Final Security Hardening

  • Hide your secret: Instead of hardcoding the secret in the script, use an environment variable for extra safety.
  • Restrict IP access: If your webhook only comes from a specific provider (like GitHub), add IP allow rules in Nginx to block other sources:
    location /webhook {
        allow 192.30.252.0/22;  # Example: GitHub's IP range
        deny all;
        # Rest of your proxy config
    }
    
  • Double-check HTTPS: You mentioned having a secure server, but confirm all webhook requests are sent over HTTPS to avoid eavesdropping.

Once everything is set up, send a test webhook request to https://your-domain.com/webhook—your Python script should trigger automatically!

内容的提问来源于stack exchange,提问作者Charles Wiktenschtien

火山引擎 最新活动