参考链接
http://www.jsutp.com/.%2fmanual/mod/mod_lua.html#luahookfixups
#vim /etc/httpd/conf/httpd.conf
LoadModule lua_module modules/mod_lua.so
LuaHookFixups /etc/httpd/lua/ip2blacklist.lua ip2blacklist
-- /etc/httpd/lua/ip2blacklist.lua --
require 'apache2'
function ip2blacklist(r)
-- 实时从 httpd asscess_log 日志 读取访问ip和根路径 不在白名单内就iptables封堵
--
local tbl = {
'404', 'api', 'images'}
local cmd = "sudo firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source address=" .. r.useragent_ip .. " drop'"
local cmd_reload = "sudo firewall-cmd --reload"
local hasIp = false
for k,v in ipairs(tbl) do
if "/"..v == r.uri then
-- 以读写方式打开文件
local blacklistFile= "/var/log/httpd/blacklist.txt"
local blacklist = io.open(blacklistFile, "a+")
for line in blacklist:lines() do
if(string.gsub(line, "\r\n", "") == r.useragent_ip) then
hasIp = true
break
end
end
print(hasIp)
if not hasIp then
-- Log stuff ourselves and don't log in the regular log
local f = io.open("/var/log/httpd/ip2blacklist.log", "a+")
if f then
blacklist:write(r.useragent_ip.."\n")
f:write("ip2blacklist===" .. r.useragent_ip .. " " .. r.method .." " .. r.uri .."\n")
f:write("cmd===" .. cmd .."\n")
f:write("cmd_reload===" .. cmd_reload .. "\n")
f:close()
-- 执行命令
os.execute(cmd)
os.execute(cmd_reload)
end
end
blacklist:close()
end
end
return apache2.OK -- Tell httpd not to use the regular logging functions
end
-- 遍历数组
function IsInTable(value, tbl)
for k,v in ipairs(tbl) do
if v == value then
return true;
end
end
return false;
end
还有需要改进的地方,再结合实际情况修改吧