← Back to all snippets
BASH

Analyzing Web Server Logs for Top Requesting IP Addresses

Quickly identify the top IP addresses accessing your web server by parsing Nginx or Apache access logs using `awk`, `sort`, and `uniq` commands for traffic analysis and security.

#!/bin/bash
LOG_FILE="/var/log/nginx/access.log" # Or /var/log/apache2/access.log
NUM_IPS=10

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

echo "Analyzing '$LOG_FILE' for top $NUM_IPS IP addresses..."
echo "------------------------------------------------"

# Extract IP addresses (assuming common log format: IP - - [date time] "request")
# awk '{print $1}' gets the first field, which is usually the IP address
grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' "$LOG_FILE" | \
awk '{print $1}' | \
sort | \
uniq -c | \
sort -nr | \
head -n "$NUM_IPS"
How it works: This script processes web server access logs (Nginx or Apache) to identify the top N IP addresses making requests. It uses `grep` for initial filtering, `awk` to extract the IP address field, `sort` to group them, `uniq -c` to count occurrences, and `sort -nr` to display them in descending order, finally showing the `head -n` top entries.

Need help integrating this into your project?

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

Hire DigitalCodeLabs