如何从Nginx运行bash脚本

8

1) 我有一个静态网站,想要设置从bitbucket的“自动拉取”。

2) 我从bitbucket有一个webhook。

3) 我有一个bash脚本执行“git pull”操作。

当nginx捕捉到请求时,如何运行此脚本?

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;
    }
}

我尝试了lua_block和fastcgi服务,但都失败了。 lua无法运行os.execute(“/path/to/script”),也无法写日志。 fastcgi比较成功,但是没有权限,因为我的www-data用户在我的bitbucket仓库中没有ssh密钥。


为什么不能通过cron运行此脚本并执行类似于s3同步的操作?这样,它只会在有更改时拉取文件。 - bob dylan
2个回答

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;
    }
}

问题出在www-data用户和它在存储库中的ssh密钥的权限上。

1
基于this,创建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()

运行它,并在nginx配置中添加。
location /autopull { proxy_pass http://localhost:8080; }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接