BASH

Analyze Nginx Access Logs for Top IP Addresses

A Bash script to parse Nginx or Apache access logs, extract the source IP addresses, and list the top N most frequent IPs.

#!/bin/bash

LOG_FILE="/var/log/nginx/access.log"
NUM_IPS=10 # Number of top IPs to display

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

echo "Analyzing $LOG_FILE for top $NUM_IPS IP addresses...
"
# Using awk to extract IP (assuming common log format where IP is the first field)
# then sort, count unique occurrences, and display top N
awk '{print $1}' "$LOG_FILE" | sort | uniq -c | sort -nr | head -n "$NUM_IPS"
echo "Analysis complete.
"
How it works: This script analyzes a specified web server access log (e.g., Nginx or Apache). It uses `awk` to extract the first field of each line, which typically contains the client's IP address in common log formats. The extracted IPs are then piped to `sort` to group identical IPs, `uniq -c` to count their occurrences, and `sort -nr` to arrange them in descending order of frequency. Finally, `head -n` displays the top N most frequent IP addresses, useful for identifying popular visitors or potential attack sources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs