圖/文:迷神
讓Nginx使用url訪問的模式,也可以執行linux的shell命令是一件很爽的事情。本文就是使用小巧的lua腳本,Nginx我使用春哥的 openresty,當然如果你自己使用原版nginx,那需要編譯下lua環境。
如果大家怕麻煩,可以使用的寶塔安裝的openresty環境。
一、我們先安裝:sockproc
sockproc 是一個伺服器程序, 偵測socket ,unix 或者 tcp , 並把收到的命令,傳遞給子進程執行,執行完畢後,把結果返回給客戶端
git clone https://github.com/juce/sockproc #git克隆代碼cd sockprocmake #編譯./sockproc /tmp/cmd.sockchmod 0666 /tmp/cmd.sock
二、下載lua-resty-shell模塊
一個很小巧的非阻塞的shell執行庫,用來配合openresty 使用,具體大家可以去github上看他使用的的demo
git clone https://github.com/juce/lua-resty-shellcd lua-resty-shellcp 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 就可以訪問啦。