local myfile = io.popen("pwd", "r") ifnil == myfile then print("open file for dir fail!!") end
print("n=========command dir result:")
-- 读取文件内容 for cnt in myfile:lines() do print(cnt) end
-- 关闭文件 myfile:close()
local secondfile = io.popen("ifconfig") ifnil == secondfile then print("open file for ifconfig fail!!") end
print("n==========command ifconfig result:")
-- 读取文件内容 local content = secondfile:read("*a") print(content)
-- 关闭文件 secondfile:close()
通过openresty的web服务提供一个接口,执行系统脚本,停止某个服务,并返回结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 调用 http://192.168.1.12/testapi?value=stop location = /testapi { default_type 'text/plain'; content_by_lua_block { local value = ngx.var.arg_value if value ~= nil then local command = "/usr/bin/bash /usr/local/src/stopService.sh "..value local handle = io.popen(command) local result = handle:read("*a") handle:close() ngx.say(result) ngx.exit(200) else ngx.exit(404) end } }
lua语法的字符串分割,自定义方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
--定义函数,分割字符串 function string.split(str, splitParameter) local result = {} string.gsub(str,'[^'..splitParameter..']+', function(w) table.insert(result, w) end) return result end
# 可能不太好理解的就是 string.gsub中使用了另一个函数
# 先看下string.gsub的使用格式 string.gsub (s, pattern, repl [,m]) # s 为原字符串, pattern 为匹配的模式 repl 替换的内容 m 只查找pattern匹配的m个子串
# 此配置简写nginx的配置文件,动态匹配url,根据文件定义proxy_pass的值 function FileRead() local file_path = "/usr/local/openresty/nginx/conf/gb/3rd/api-pay-env.conf" local file = io.open(file_path, "r") for line in file:lines() do local splitValues = string.split(line, "=") if splitValues[1] == location_uri then -- 判断访问的location匹配的uri 是否存在文件 local proxy_pass_split = string.split(splitValues[2], "/")[2] -- 获取proxy_pass中的host,将端口去掉 local valueMatch = string.match(proxy_pass_split, ":") if valueMatch ~= nil then local proxy_pass_split = string.split(proxy_pass_split, ":")[1] end
ngx.var.query_host = proxy_pass_split -- 修改nginx设置的query_host值,用于proxy_set_header Host $query_host; local uri = ngx.re.sub(ngx.var.request_uri, "^/.*-api/(.*)", "$1", "o") local resultProxyPass = splitValues[2] .. uri ngx.log(ngx.ERR, "set_host的值: ", proxy_pass_split) ngx.log(ngx.ERR, "proxy_pass的值: ", resultProxyPass) return resultProxyPass end end end
--获取location匹配的url --定义函数,分割url路径 function(str, splitParameter) local result = {} string.gsub(str,'[^'..splitParameter..']+', function(w)table.insert(result, w) end) return result end
local request_uri = ngx.var.uri --获取访问的url,不带参数 local location_uri = string.split(request_uri, "/")[1]
nginx修改客户访问的uri
1 2 3 4 5
rewrite_by_lua' local uri = ngx.re.sub(ngx.var.request_uri, "^/.*-api/(.*)", "/$1", "o") ngx.req.set_uri(uri) ngx.log(ngx.ERR, "set_uri: ", uri) ';