编程技术分享平台

网站首页 > 技术教程 正文

Lua新奇玩法,让Nginx也可以执行linux的shell命令

xnh888 2024-09-08 10:56:17 技术教程 171 ℃ 0 评论

图/文:迷神

让Nginx使用url访问的模式,也可以执行linux的shell命令是一件很爽的事情。本文就是使用小巧的lua脚本,Nginx我使用春哥的 openresty,当然如果你自己使用原版nginx,那需要编译下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 使用,具体大家可以去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,通过http://你的IP/api/ls 就可以访问啦。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表