图/文:迷神
让Nginx使用url访问的模式linux执行sh文件linux空间,也可以执行linux的shell命令是一件很爽的事情。本文就是使用精巧的lua脚本,Nginx我使用春哥的openresty,其实假如你自己使用原版nginxlinux执行sh文件,那须要编译下lua环境。
假如你们怕麻烦,可以使用的宝塔安装的openresty环境。
一、我们先安装:sockproc
sockproc是一个服务器程序,探测socket,unix或则tcp,并把收到的命令,传递给子进程执行,执行完毕后,把结果返回给顾客端
git clone https://github.com/juce/sockproc #git克隆代码
cd sockproc
make #编译
./sockproc /tmp/cmd.sock
chmod 0666 /tmp/cmd.sock
二、下载lua-resty-shell模块
一个很精巧的非阻塞的shell执行库,拿来配合openresty使用linux防火墙设置,具体你们可以去github上看他使用的的demo
git clone https://github.com/juce/lua-resty-shell
cd lua-resty-shell
cp lib/resty/shell.lua /openresty/lualib/resty/ #这是你的项目路径
创建lua脚本
vi /openresty/lualib/cmd.lua --创建文件command.lua,输入下面代码
local shell = require "resty.shell"
local args = {
socket = "unix:/tmp/cmd.sock", --这是第一步的unxi socket
}

local status, out, err = shell.execute("ls", args) --ls 是想调用的命令,
ngx.header.content_type = "text/plain"
ngx.say("Result:n" .. out) -- 命令输出结果
三、写入nginx配置
vi /openresty/nginx/conf/nginx.conf
#增加一个localtion 配置
location = /api/ls {
content_by_lua_file /southtv/openresty/lualib/cmd.lua;
}
之后重启下openresty,通过你的IP/api/ls就可以访问啦。