利用nginx执行Shell 脚本,nginx执行shell脚本


利用nginx执行shell脚本

通过远程url调用Shell 命令是很爽的事情,可以解决很多问题. 况且本文介绍的方法是非阻塞的, 也就是说可以很多并发调用,无论你的命令执行时间多久, 并不会导致web服务阻塞异常.

首先自行安装openresty,不做介绍了就.
假如我们安装路径为:/southtv/openresty

1 首先安装sockproc

git clone https://github.com/juce/sockproc
cd sockproc
make
./sockproc /tmp/shell.sock
chmod 0666 /tmp/shell.sock

sockproc 是一个服务器程序, 侦测unix socket 或者 tcp socket , 并把收到的命令,传递给子进程执行,执行完毕后,把结果返回给客户端, 我们就让sockproc 侦测/tmp/shell.sock 的套接口有没有数据到来.

2 安装lua-resty-shell模块.

它是一个很小的库, 配合openresty 使用, 目的是提供类似于os.execute 或io.popen的功能, 唯一区别它是非阻塞的, 也就是说即使需要耗时很久的命令,你也可以使用它

git clone https://github.com/juce/lua-resty-shell
cd lua-resty-shell
cp lib/resty/shell.lua /southtv/openresty/lualib/resty/  这是你的项目路径

3 创建自己的命令调用lua 脚本

vim /southtv/openresty/lualib/command.lua    --名字我起名为command.lua
local shell = require "resty.shell"
   local args = {
            socket = "unix:/tmp/shell.sock",  --这是第一步的unxi socket
   }
local status, out, err = shell.execute("ls", args)  --ls 是想调用的命令,
ngx.header.content_type = "text/plain"
ngx.say("Result:\n" .. out)                    -- 命令输出结果

4 更改nginx 配置

vim /southtv/openresty/nginx/conf/nginx.conf
#增加一个localtion 配置
location = /api/ls {
            content_by_lua_file /southtv/openresty/lualib/command.lua;
 }

重启 nginx

/southtv/openresty/nginx/sbin/nginx -s reload

5 测试效果了
可以用浏览器直接打开: http://你的IP/api/ls
可以看到你期望的结果了.

欢迎下载使用 南方无线电视
[ 南方无线APP ]

相关内容

    暂无相关文章