Openresty通过Lua+Redis 实现动态封禁IP

news/2025/2/21 4:26:11/
求背景

为了封禁某些爬虫或者恶意用户对服务器的请求,我们需要建立一个动态的 IP 黑名单。对于黑名单之内的 IP ,拒绝提供服务。并且可以设置失效

1.安装Openresty(编译安装)

wget https://openresty.org/download/openresty-1.19.3.1.tar.gz
# 解压openresty
tar -zxvf openresty-1.19.3.1.tar.gz 

下载缓存插件
 

wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz#解压缓存插件
tar -zxvf ngx_cache_purge-2.3.tar.gz
cd openresty-1.19.3.1/
mkdir modules
# 把刚解压的ngx_cache_purge移动到该目录下

安装依赖

yum install pcre-devel openssl-devel gcc curl -y

编译OpenResty

选择需要的插件启用, –with-Components 激活组件,–without 则是禁止组件 ,–add-module是安装第三方模块。
进入刚刚解压好的openresty-1.19.3.1根目录下执行命令

./configure --prefix=/usr/local/openresty --with-luajit --without-http_redis2_module --with-http_stub_status_module --with-http_v2_module --with-http_gzip_static_module --with-http_sub_module --add-module=/usr/local/openresty-1.19.3.1/modules/ngx_cache_purge-2.3 

–prefix=/usr/local/openresty: 刚自己创建的目录,用来存放编译后的openresty
–add-module=/usr/local/openresty-1.19.3.1/xxx: 存放第三方插件的位置

2.安装redis

这里我是基于docker安装的redis 

docker run --restart=always -p 6379:6379 --name myredis -d redis:7.0.12  --requirepass xxx

- -requirepass 是redis密码

3.写lua脚本

ip_bind_time = 30  --封禁IP多长时间
ip_time_out = 6    --指定统计ip访问频率时间范围
connect_count = 10 --指定ip访问频率计数最大值
--上面的意思就是6秒内访问超过10次,自动封 IP 30秒。--连接redis
local redis = require "resty.redis"
local cache = redis.new()
local ok , err = cache.connect(cache,"127.0.0.1","6379")
-- redis密码
local res, err = cache:auth("xxx")
cache:set_timeout(60000)--如果连接失败,跳转到脚本结尾
if not ok thengoto Lastend
end--查询ip是否在封禁段内,若在则返回403错误代码
--因封禁时间会大于ip记录时间,故此处不对ip时间key和计数key做处理
is_bind , err = cache:get("bind_"..ngx.var.remote_addr)if is_bind == '1' thenngx.exit(ngx.HTTP_FORBIDDEN)-- 或者 ngx.exit(403)-- 当然,你也可以返回500错误啥的,搞一个500页面,提示,亲您访问太频繁啥的。goto Lastend
endstart_time , err = cache:get("time_"..ngx.var.remote_addr)
ip_count , err = cache:get("count_"..ngx.var.remote_addr)--如果ip记录时间大于指定时间间隔或者记录时间或者不存在ip时间key则重置时间key和计数key
--如果ip时间key小于时间间隔,则ip计数+1,且如果ip计数大于ip频率计数,则设置ip的封禁key为1
--同时设置封禁key的过期时间为封禁ip的时间if start_time == ngx.null or os.time() - start_time > ip_time_out thenres , err = cache:set("time_"..ngx.var.remote_addr , os.time())res , err = cache:set("count_"..ngx.var.remote_addr , 1)
elseip_count = ip_count + 1res , err = cache:incr("count_"..ngx.var.remote_addr)if ip_count >= connect_count thenres , err = cache:set("bind_"..ngx.var.remote_addr,1)res , err = cache:expire("bind_"..ngx.var.remote_addr,ip_bind_time) --fix keysend
end
--结尾标记
::Lastend::
local ok, err = cache:close()
#user  nobody;
worker_processes  1;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {worker_connections  1024;
}http {include       mime.types;default_type  application/octet-stream;#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '#                  '$status $body_bytes_sent "$http_referer" '#                  '"$http_user_agent" "$http_x_forwarded_for"';#access_log  logs/access.log  main;sendfile        on;#tcp_nopush     on;#keepalive_timeout  0;keepalive_timeout  65;#gzip  on;server {listen       80;server_name  localhost;#charset koi8-r;#access_log  logs/host.access.log  main;location / {root   html;index  index.html index.htm;access_by_lua_file "/usr/local/openresty/nginx/lua/access_by_redis.lua";}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {#    proxy_pass   http://127.0.0.1;#}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##location ~ \.php$ {#    root           html;#    fastcgi_pass   127.0.0.1:9000;#    fastcgi_index  index.php;#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;#    include        fastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {#    deny  all;#}}# another virtual host using mix of IP-, name-, and port-based configuration##server {#    listen       8000;#    listen       somename:8080;#    server_name  somename  alias  another.alias;#    location / {#        root   html;#        index  index.html index.htm;#    }#}# HTTPS server##server {#    listen       443 ssl;#    server_name  localhost;#    ssl_certificate      cert.pem;#    ssl_certificate_key  cert.key;#    ssl_session_cache    shared:SSL:1m;#    ssl_session_timeout  5m;#    ssl_ciphers  HIGH:!aNULL:!MD5;#    ssl_prefer_server_ciphers  on;#    location / {#        root   html;#        index  index.html index.htm;#    }#}}

启动下就可以了


http://www.ppmy.cn/news/1131578.html

相关文章

pytorch第一天(tensor数据和csv数据的预处理)lm老师版

tensor数据: import torch import numpyx torch.arange(12) print(x) print(x.shape) print(x.numel())X x.reshape(3, 4) print(X)zeros torch.zeros((2, 3, 4)) print(zeros)ones torch.ones((2,3,4)) print(ones)randon torch.randn(3,4) print(randon)a …

Scala第九章节

Scala第九章节 scala总目录 章节目标 理解包的相关内容掌握样例类, 样例对象的使用掌握计算器案例 1. 包 实际开发中, 我们肯定会遇到同名的类, 例如: 两个Person类. 那在不改变类名的情况下, 如何区分它们呢? 这就要使用到包(package)了. 1.1 简介 包就是文件夹, 用关…

Linux系统编程系列之进程间通信-消息队列

一、什么是消息队列 消息队列是system-V三种IPC对象之一,是进程间通信的一种方式。 二、消息队列的特性 允许发送的数据携带类型(指定发送给谁),具有相同类型的数据在消息队列内部排队,读取的时候也要指定类型&#x…

步进电机驱动时如何计算90°相位差对应的CCR

对于步进电机的两路驱动PWM脉冲,通常需要保持它们的相位差在90以确保电机正常运转。在这种情况下,相位差通常是一个固定值,并且可以通过设置定时器的比较寄存器(CCR)来实现。 以下是计算CCR值的一般步骤: …

[AIGC] 快速掌握Netty,打造高性能IM服务器!

前言:Netty 是一个非常优秀的网络应用程序框架,支持高并发、高性能的网络通信,适用于开发各种服务器程序,如即时通讯、游戏、物联网等。使用 Netty 可以大大提升服务器程序的性能和可靠性。本文将介绍 Netty 的基本原理和使用方法…

第 114 场 LeetCode 双周赛题解

A 收集元素的最少操作次数 模拟: 反序遍历数组&#xff0c;用一个集合存当前遍历过的不超过 k k k 的正数 class Solution { public:int minOperations(vector<int> &nums, int k) {unordered_set<int> vis;int n nums.size();int i n - 1;for (;; i--) {if…

设计模式之抽象工厂模式--创建一系列相关对象的艺术(简单工厂、工厂方法、到抽象工厂的进化过程,类图NS图)

目录 概述概念适用场景结构类图 衍化过程业务需求基本的数据访问程序工厂方法实现数据访问程序抽象工厂实现数据访问程序简单工厂改进抽象工厂使用反射抽象工厂反射配置文件衍化过程总结 常见问题总结 概述 概念 抽象工厂模式是一种创建型设计模式&#xff0c;它提供了一种将相…

GD32F10x的输出模式

1. 单片机型号的识别。 2. GPIO的输出模式。 1. 开漏模式 2.推挽模式 3.复用开漏模式 4.复用推挽模式。 开漏模式&#xff1a;&#xff08;写入位设置&#xff0c;输出数据寄存器来控制MOS&#xff09; 只有N-MOS管导通。PMOS不导通。 当N-MOS的栅极为0&#xff0c;N-MOS管…