本文基于Centos7验证,其中文中nginx使用的是wlnmp一键安装包(默认集成lua),当然你也可以用openresty,如果使用openresty那么文中有些配置方式可能不适用,需要自行调整,建议使用https://www.wlnmp.com/来安装nginx。
生产环境不建议这么”玩“,风险非常大,如果非要玩,可以考虑添加401认证。
1、安装一些所需依赖
1 |
yum install gcc gcc-c++ git |
2、安装sockproc
方法一:
1 2 3 4 5 |
wget https://down.whsir.com/downloads/sockproc.tar.gz tar xf sockproc.tar.gz cd sockproc make cp sockproc /usr/bin/sockproc |
方法二:
1 2 3 4 |
git clone https://github.com/juce/sockproc cd sockproc make cp sockproc /usr/bin/sockproc |
3、通过socket方式启动服务
1 |
sockproc /tmp/shell.sock && chmod 666 /tmp/shell.sock |
4、安装nginx
1 2 |
rpm -ivh https://mirrors.wlnmp.com/centos/wlnmp-release-centos.noarch.rpm yum install wnginx |
5、安装lua-resty-shell模块
先创建resty目录
1 |
mkdir /usr/local/nginx/conf/waf/resty |
方法一:
直接执行以下命令即可
1 |
curl -o /usr/local/nginx/conf/waf/resty/shell.lua https://down.whsir.com/downloads/shell.lua |
方法二:
1 2 3 |
git clone https://github.com/juce/lua-resty-shell cd lua-resty-shell cp lib/resty/shell.lua /usr/local/nginx/conf/waf/resty/ |
6、编写lua脚本
1 |
vi /usr/local/nginx/conf/waf/sh.lua |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
local uri = ngx.var.uri; local args = ngx.req.get_uri_args(); local sh = args["sh"]; local shellCommand =" "..sh local shell = require "resty.shell" local args = { socket = "unix:/tmp/shell.sock"; } local status, out, err = shell.execute(shellCommand, args) ngx.header.content_type = "text/plain" if out == nil or out == '' then ngx.say("Result:"..shellCommand.."\n") else ngx.say("Result:"..shellCommand.."\n" .. out) end |
7、开启nginx的lua支持
1 |
vi /usr/local/nginx/conf/nginx.conf |
取消以下两行前面#号注释,开启lua支持
lua_package_path "/usr/local/nginx/conf/waf/?.lua";
lua_shared_dict limit 10m;
8、配置lua访问路径
1 |
vi /usr/local/nginx/conf/vhost/demo.conf |
1 2 3 4 5 6 7 8 9 |
server { listen 80; server_name _; location = /api/shell { content_by_lua_file /usr/local/nginx/conf/waf/sh.lua; } } |
9、重启nginx,访问以下地址测试效果
1 |
/etc/init.d/nginx restart |
http://IP/api/shell?sh=date
注:我这里是通过浏览器执行date命令,你可以把date换成任意命令,例如查看nginx进程
http://IP/api/shell?sh=ps aux | grep nginx
原文链接:通过nginx代理请求执行linux命令,转载请注明来源!