nginx 如何在每个请求上运行shell脚本?

h43kikqp  于 5个月前  发布在  Nginx
关注(0)|答案(6)|浏览(92)

我想在每次我的nginx服务器收到任何HTTP请求时运行一个shell脚本。有什么简单的方法吗?

szqfcxe2

szqfcxe21#

您可以通过nginx.conf文件中的Lua代码执行shell脚本来实现这一点。您需要拥有HttpLuaModule才能做到这一点。
这里有一个例子来做这件事。

location /my-website {
  content_by_lua_block {
    os.execute("/bin/myShellScript.sh")
  } 
}

字符串

cld4siwp

cld4siwp2#

我在这个地址的网上找到了以下信息:https://www.ruby-forum.com/topic/2960191
这确实需要你在机器上安装fcgiwrap。它真的很简单:

sudo apt-get install fcgiwrap

字符串
示例脚本(必须是可执行的)

#!/bin/sh
# -*- coding: utf-8 -*-
NAME=`"cpuinfo"`
echo "Content-type:text/html\r\n"
echo "<html><head>"
echo "<title>$NAME</title>"
echo '<meta name="description" content="'$NAME'">'
echo '<meta name="keywords" content="'$NAME'">'
echo '<meta http-equiv="Content-type"
content="text/html;charset=UTF-8">'
echo '<meta name="ROBOTS" content="noindex">'
echo "</head><body><pre>"
date
echo "\nuname -a"
uname -a
echo "\ncpuinfo"
cat /proc/cpuinfo
echo "</pre></body></html>"


也可以将其用作包含文件,而不仅仅限于shell脚本。

location ~ (\.cgi|\.py|\.sh|\.pl|\.lua)$ {
    gzip off;
    root /var/www/$server_name;
    autoindex on;
    fastcgi_pass unix:/var/run/fcgiwrap.socket;
    include /etc/nginx/fastcgi_params;
    fastcgi_param DOCUMENT_ROOT /var/www/$server_name;
    fastcgi_param SCRIPT_FILENAME /var/www/$server_name$fastcgi_script_name;
}


我发现它对我的工作非常有帮助,我希望它能帮助你完成RaspberryPI项目。

ezykj2lf

ezykj2lf3#

如果你更喜欢Python中的完全控制:

  • 创建/opt/httpbot.py
#!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
import subprocess

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self._handle()

    def do_POST(self):
        self._handle()

    def _handle(self):
        try:
            self.log_message("command: %s", self.path)
            if self.path == '/foo':
                subprocess.run(
                    "cd /opt/bar && GIT_SSH_COMMAND='ssh -i .ssh/id_rsa' git pull",
                    shell=True,
                )
        finally:
            self.send_response(200)
            self.send_header("content-type", "application/json")
            self.end_headers()
            self.wfile.write('{"ok": true}\r\n'.encode())

if __name__ == "__main__":
    HTTPServer(("127.0.0.1", 4242), Handler).serve_forever()

字符串

  • 这里没有并发/并行,所以httpbot一次运行一个命令,没有冲突。
  • 运行apt install supervisor
  • 创建/etc/supervisor/conf.d/httpbot.conf
[program:httpbot]
environment=PYTHONUNBUFFERED="TRUE"
directory=/opt
command=/opt/httpbot.py
autorestart=true
redirect_stderr=true
stdout_logfile=/var/log/httpbot.log
stdout_logfile_maxbytes=1MB
stdout_logfile_backups=10

  • 添加到您的nginx服务器:
location /foo {
        proxy_pass http://127.0.0.1:4242/foo;
    }

  • 运行:
chmod u+x /opt/httpbot.py

service supervisor status
# If stopped:
service supervisor start

supervisorctl status
# If httpbot is not running:
supervisorctl update

curl https://example.com/foo
# Should return {"ok": true}

tail /var/log/httpbot.log
# Should show `command: /foo` and the output of shell script

bsxbgnwa

bsxbgnwa4#

1.安装OpenResty(OpenResty只是Nginx的一个增强版本,通过插件模块)参考https://openresty.org/en/getting-started.html
1.在示例上配置AWS服务器
1.编写shell脚本,从指定的S3存储桶下载文件
1.在nginx.conf文件中进行所需的更改
1.重启nginx服务器
我已经使用curl测试了http请求,并在相应示例的/tmp目录中下载文件:

curl -I http://localhost:8080/

字符串
输出:

curl -I http://localhost:8080/
HTTP/1.1 200 OK
Server: openresty/1.13.6.2
Date: Tue, 14 Aug 2018 07:34:49 GMT
Content-Type: text/plain
Connection: keep-alive


nginx.conf文件的内容:

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    server {
        listen 8080;
        location / {
           default_type text/html;
           content_by_lua '
                ngx.say("<p>hello, world</p>")
           ';
        }

        location / {
            content_by_lua_block{
            os.execute("sh /tmp/s3.sh")
            }
        }

    }
}

ekqde3dh

ekqde3dh5#

你可以使用nginx的perl模块,它通常是repo的一部分,可以很容易地安装。调用系统curl命令的示例:

location /mint {
       perl '
            sub {
               my $r = shift;
               $r->send_http_header("text/html");
               $r->print(`curl -X POST --data \'{"method":"evm_mine"}\' localhost:7545`);
               return OK;
            }
       '; 
}

字符串

l3zydbqr

l3zydbqr6#

你也可以使用nginx镜像模块和proxy_pass它到一个运行任何东西的web脚本。在我的情况下,我只是把这个添加到我的主站点位置,{...

mirror /mirror;
mirror_request_body off;

字符串
然后做了一个新的位置称为镜像,我已经运行了一个PHP脚本,执行任何.

location = /mirror {
    internal;
    proxy_pass http://localhost/run_script.php;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
}


https://nginx.org/en/docs/http/ngx_http_mirror_module.html

相关问题