nginx自动屏蔽不友好的ip

查看nginx日志的时候发现大量的404302尝试访问不存在的资源,大概率是使用工具扫描。

{"connection": "2572288","pid": "176228","request_id": "7d5dcaac3e4be47a536a4a0d1b5c7abb","request_length": "157","remote_addr": "52.170.115.255","time_local": "08/Apr/2022:17:44:50 +0800","status":"302","host":"fengqi.me","uri":"/Panels.txt","server":"fengqi.me","port":"443","protocol":"HTTP/1.1","request_uri":"/Panels.txt","args": "","scheme": "https","request_time": "0.000","request_method":"GET","http_referrer":"","body_bytes_sent":"138","http_x_forwarded_for":"","http_user_agent":"python-requests/2.27.1","upstream_response_time":""}
{"connection": "2572337","pid": "176261","request_id": "cf56fa6708c4b68d1b8e3b4d7871103c","request_length": "150","remote_addr": "52.170.115.255","time_local": "08/Apr/2022:17:45:09 +0800","status":"302","host":"fengqi.me","uri":"/Panels.txt","server":"fengqi.me","port":"443","protocol":"HTTP/1.1","request_uri":"/Panels.txt","args": "","scheme": "https","request_time": "0.000","request_method":"GET","http_referrer":"","body_bytes_sent":"146","http_x_forwarded_for":"","http_user_agent":"python-requests/2.27.1","upstream_response_time":""}
{"connection": "2186500","pid": "164519","request_id": "aa21defaa0a590422420732b52c58f83","request_length": "253","remote_addr": "13.93.105.179","time_local": "08/Apr/2022:16:18:21 +0800","status":"302","host":"fengqi.me","uri":"/new-index.php","server":"fengqi.me","port":"443","protocol":"HTTP/1.1","request_uri":"/new-index.php","args": "","scheme": "https","request_time": "0.000","request_method":"GET","http_referrer":"","body_bytes_sent":"138","http_x_forwarded_for":"","http_user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36","upstream_response_time":""}

正常用户不会这么访问,所以基本上一个ip重复来这么几次就是有问题的,写个脚本,定时扫描nginxaccess.log统计出频繁的ip,然后干掉。

脚本内容解释:

  • tail -n $line 是用来控制分析最近多少条的日志
  • times 用来控制一个IP重复多少次才干掉
  • conf 是生成的屏蔽列表文件路径,需要在nginx.conf内引入

放到crontab内,每小时执行一次就行了,有些脚本小子可能刷一会儿就换ip,可以缩小执行的频率和条数。

参考

http://www.zuobin.net/2016/05/338.html

标签: nginx, deny

添加新评论