BASH
Extract Top IP Addresses from Access Logs
Learn to parse Apache or Nginx access logs using bash, awk, and sort to identify and count the most frequent IP addresses accessing your web server.
#!/bin/bash
# Configuration
ACCESS_LOG="/var/log/apache2/access.log" # Path to your access log file
TOP_N=10 # Number of top IPs to display
# Check if log file exists
if [ ! -f "$ACCESS_LOG" ]; then
echo "Error: Access log file '$ACCESS_LOG' not found."
exit 1
fi
echo "Analyzing top $TOP_N IP addresses from $ACCESS_LOG..."
# Extract IP addresses, count occurrences, and display top N
# awk '{print $1}' : Extracts the first field (IP address)
# sort : Sorts the IPs to group identical ones
# uniq -c : Counts contiguous identical lines
# sort -nr : Sorts numerically in reverse (highest count first)
# head -n $TOP_N: Displays only the top N results
awk '{print $1}' "$ACCESS_LOG" | sort | uniq -c | sort -nr | head -n "$TOP_N"
if [ $? -eq 0 ]; then
echo "Analysis completed successfully."
else
echo "Analysis encountered errors."
fi
How it works: This script analyzes web server access logs to identify the most frequent IP addresses. It reads the 'ACCESS_LOG' file, uses 'awk' to extract the first field (which is typically the IP address), then pipes the output through 'sort' to group identical IPs. 'uniq -c' counts the occurrences, and 'sort -nr' orders them from most to least frequent. Finally, 'head -n $TOP_N' displays only the specified number of top IPs, useful for security monitoring or traffic analysis.