如何从 Nginx 运行 bash 脚本

Vad*_*lov 8 git bash nginx

1)我有静态站点和魔杖来从bitbucket设置“自动拉取”。

2)我有来自bitbucket的webhook。

3)我有 bash 脚本,可以执行“git pull”

当 nginx catch 请求时如何运行这个脚本?

server {

    listen   80;
    server_name example.ru;

    root /path/to/root;
    index index.html;

    access_log /path/to/logs/nginx-access.log;
    error_log /path/to/logs/nginx-error.log;

    location /autopull {
        something to run autopull.sh;
    }

    location / {
        auth_basic "Hello, login please";
        auth_basic_user_file /path/to/htpasswd;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header Host $host;
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了 lua_block 和 fastcgi 服务,但都失败了。lua 不运行 os.execute("/path/to/script") 并且不写入日志。fastcgi 更成功,但它没有权限,因为我的 www-data 用户在我的 bitbuchet 存储库中没有 ssh-key 。

Vad*_*lov 5

问题解决了。

我不想在另一个端口上使用任何脚本/进程,因为我有几个站点,每个站点都需要端口。

我的最终配置是:

server {

    listen   80;
    server_name example.ru;

    root /path/to/project;
    index index.html;

    access_log /path/to/logs/nginx-access.log;
    error_log /path/to/logs/nginx-error.log;

    location /autopull {
        content_by_lua_block {
            io.popen("bash /path/to/autopull.sh")
        }
    }

    location / {
        auth_basic "Hello, login please";
        auth_basic_user_file /path/to/htpasswd;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header Host $host;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题出在存储库中 www-data 用户及其 ssh-kay 的许可上。


Iva*_*van 1

在此基础上,创建py脚本

#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from subprocess import call

PORT_NUMBER = 8080
autopull = '/path/to/autopull.sh'
command = [autopull]

#This class will handles any incoming request from
#the browser 
class myHandler(BaseHTTPRequestHandler):

    #Handler for the GET requests
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        # Send the html message
        self.wfile.write("runing {}".format(autopull))
        call(command)
        return

try:
    #Create a web server and define the handler to manage the
    #incoming request
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ' , PORT_NUMBER

    #Wait forever for incoming htto requests
    server.serve_forever()

except KeyboardInterrupt:
    print '^C received, shutting down the web server'
    server.socket.close()
Run Code Online (Sandbox Code Playgroud)

运行它并在 nginx 配置中添加

location /autopull { proxy_pass http://localhost:8080; }
Run Code Online (Sandbox Code Playgroud)