lua脚本

#centos6
  #安装cjson报错的话检查lua-cjson-2.1.0编译后的cjson库文件,/usr/lib64/lua/5.1里要有cjson
#centos7
  #yum install luarocks
  #luarocks install lua-cjson
  #以下路径要有cjson.so文件,否则有可能用lua执行脚本是成功的,但是nginx执行lua脚本报错
    /usr/lib64/lua/5.1/cjson.so
    /usr/local/luajit/lib/lua/5.1/cjson.so
    /usr/local/luajit/share/luajit-2.0.4/cjson.so



local post_data = ngx.req.get_body_data() --[[ngx.log(ngx.ERR, 'post data:', post_data)]] local ok, res_tab = pcall(cjson.decode, post_data) if not ok then ngx.log(ngx.ERR, 'post data is not json!', post_data) get_respone(Result_Code.Error) return end -- 真正判断是否json post_data = string.gsub(post_data,"\"{","{") post_data = string.gsub(post_data,"}\"","}") post_data = string.gsub(post_data,"\\","") local ok, res_tab = pcall(cjson.decode, post_data) if not ok then ngx.log(ngx.ERR, 'post data is not json!', post_data) get_respone(Result_Code.Error) return end

 

 

根据appId来封禁post访问,appId存在文件中,由于需要封禁的appId较多,需要通过lua读取文件来实现

[root@VM-0-15-centos vhost]# cat test.lua 
local cjson = require("cjson")
local obj = cjson.new()
if ngx.var.request_method == "POST" then
    ngx.req.read_body()
    local args = ngx.req.get_body_data()
    local ok, res_tab = pcall(cjson.decode, args)
    if ok then
        for line in io.lines("/usr/local/nginx/conf/vhost/1.txt") do
            local res = cjson.decode(args)
            if res['appId'] then
                if line == res['appId'] then
                    ngx.say(500)
                end
            end
        io.close()
        end
    end
end

 

 

1.如果是post请求

2.并且请求的url是  /device/v1/register  或者   /device/v1/sregister

3.判断是否是json格式,如果是就转化成table格式

4.判断appid是否跟文件内容能匹配

if ngx.var.request_method == "POST" then
    ngx.req.read_body()
    local request_uri = ngx.var.request_uri
    if string.match(request_uri,"/device/v1/register") or string.match(request_uri,"/device/v1/sregister") then
        local cjson = require("cjson")
        local obj = cjson.new()
        local args = ngx.req.get_body_data()
        local ok,res_tab = pcall(cjson.decode,args)
        if ok then
            for line in io.lines("/usr/local/nginx/conf/vhost/black_list.txt") do
                local res = cjson.decode(args)
                if res['agentId'] == line then
                    ngx.say(500)
                end
            end
            io.close()
        end
    end
end

 

posted @ 2022-11-24 22:36  力王7314  阅读(395)  评论(0编辑  收藏  举报