插件窝 干货文章 如何用Nginx日志监控恶意访问

如何用Nginx日志监控恶意访问

Nginx log 访问 access 817    来源:    2025-05-05

使用Nginx日志监控恶意访问的方法

监控Nginx日志中的恶意访问是保护网站安全的重要措施。以下是几种有效的方法:

1. 分析Nginx访问日志

Nginx访问日志(通常位于/var/log/nginx/access.log)包含大量有价值的信息:

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
               '$status $body_bytes_sent "$http_referer" '
               '"$http_user_agent" "$http_x_forwarded_for"';

2. 使用工具实时监控

使用grep命令快速筛查

# 查找频繁访问的IP
cat /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr

# 查找特定攻击模式
grep -i "select.*from" /var/log/nginx/access.log
grep -i "union.*select" /var/log/nginx/access.log
grep -i "etc/passwd" /var/log/nginx/access.log
grep -i "wp-login.php" /var/log/nginx/access.log

使用Fail2Ban自动封禁

Fail2Ban可以自动分析日志并封禁恶意IP:

  1. 安装Fail2Ban
sudo apt-get install fail2ban  # Debian/Ubuntu
sudo yum install fail2ban      # CentOS/RHEL
  1. 配置Nginx规则
# /etc/fail2ban/jail.local
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port    = http,https
logpath = /var/log/nginx/error.log

[nginx-badbots]
enabled  = true
filter   = nginx-badbots
port     = http,https
logpath  = /var/log/nginx/access.log
maxretry = 2

3. 使用ELK Stack进行高级分析

Elasticsearch + Logstash + Kibana (ELK) 堆栈可以提供强大的日志分析能力:

  1. 配置Logstash处理Nginx日志
input {
  file {
    path => "/var/log/nginx/access.log"
    start_position => "beginning"
  }
}

filter {
  grok {
    match => { "message" => "%{COMBINEDAPACHELOG}" }
  }
  geoip {
    source => "clientip"
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
  }
}
  1. 在Kibana中创建可视化仪表板监控:
    • 请求频率异常高的IP
    • 404错误最多的URL
    • 可疑User-Agent
    • 来自特定国家的异常访问

4. 使用GoAccess实时分析

GoAccess是一个实时的Web日志分析器:

goaccess /var/log/nginx/access.log --log-format=COMBINED

5. 自定义监控脚本

编写Python脚本分析日志:

import collections
import re

def analyze_log(logfile):
    ip_counter = collections.Counter()
    with open(logfile) as f:
        for line in f:
            ip = line.split()[0]
            ip_counter[ip] += 1
            # 检测SQL注入尝试
            if re.search(r'union.*select|select.*from|insert into|drop table', line, re.I):
                print(f"可能的SQL注入尝试: {line.strip()}")

    print("\n访问最频繁的IP:")
    for ip, count in ip_counter.most_common(10):
        print(f"{ip}: {count}次")

analyze_log('/var/log/nginx/access.log')

6. 常见恶意访问特征

需要特别关注的日志特征: - 短时间内大量404错误 - 扫描常见漏洞的URL (如/wp-admin, /phpmyadmin) - 异常的User-Agent (如扫描器、自动化工具) - 包含特殊字符的请求 (如../, %, ', ") - 来自单一IP的高频访问 - 非正常时段的访问高峰

通过以上方法,您可以有效地监控和识别Nginx日志中的恶意访问行为,及时采取防护措施。