执行shell命令

安装 sockproc

  1. # 安装sockproc
  2. git clone https://github.com/juce/sockproc.git
  3. cd sockproc/
  4. gcc -o sockproc ./sockproc.c
  5. # 创建Unix套接字,提供给lua的shell库连接
  6. ./sockproc /tmp/shell.sock
  7. chmod 0666 /tmp/shell.sock

安装 lua-resty-shell

  1. git clone https://github.com/juce/lua-resty-shell
  2. # 复制库到openresty下
  3. cp lua-resty-shell/lib/resty/shell.lua /usr/local/openresty/lualib/resty/

修改nginx配置文件

  • vi /usr/local/openresty/nginx/conf/nginx.conf ,在 server 节点下加入如下内容:
  1. location /shell_test {
  2. content_by_lua_block {
  3. local shell = require("resty.shell")
  4. local args = {
  5. socket = "unix:/tmp/shell.sock",
  6. }
  7. local status, out, err = shell.execute("uname -a", args)
  8. ngx.header.content_type = "text/plain"
  9. ngx.say("Hello from:\n" .. out)
  10. }
  11. }
  • 重启 openresty - /usr/local/openresty/bin/openresty -s reload
  • 访问地址 /shell_test

image.png