BASH

Extract Top IPs from Nginx Access Logs

Analyze Nginx access logs to identify and count the top client IP addresses making requests, useful for traffic analysis or identifying potential threats.

#!/bin/bash

# Configuration
LOG_FILE="/var/log/nginx/access.log"
NUM_IPS=10

if [ ! -f "$LOG_FILE" ]; then
    echo "Error: Log file '$LOG_FILE' not found."
    exit 1
fi

echo "Top $NUM_IPS IP Addresses accessing the web server:"

# Extract IP addresses, sort them, count unique occurrences, and display top N
grep -oE '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' "$LOG_FILE" | \
sort | \
uniq -c | \
sort -rn | \
head -n "$NUM_IPS"

if [ $? -eq 0 ]; then
    echo "Log analysis completed successfully."
else
    echo "Log analysis failed."
fi
How it works: This script parses an Nginx access log file to extract and count the occurrences of client IP addresses. It uses `grep` with a regular expression to isolate IPs, `sort` to group identical IPs, `uniq -c` to count them, another `sort -rn` to order by count descending, and `head` to display the top `N` results. This is useful for traffic analysis, identifying popular clients, or detecting potential DoS attacks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs