how to parse nginx log in cli, and show count, url, ip and user agent, sorted by count…
- User
how to parse nginx log in cli, and show count, url, ip and user agent, sorted by count desc
- Assistant
how to parse nginx log in cli, and show count, url, ip and user agent, sorted by count desc
To parse an Nginx log and display the count, URL, IP, and User Agent sorted by count in descending order using the command line, you can use a combination of tools like awk, sort, uniq, and head. Here's a step-by-step example assuming your Nginx log format includes standard fields.
Suppose your Nginx access log (access.log) has entries like this:
127.0.0.1 - - [10/Oct/2023:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 612 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
Use the following command to extract and count the specified fields:
Extract Relevant Fields:
We will use awk to extract the IP, URL, and User Agent from each log entry.
Sort and Count Unique Entries:
Use sort and uniq to count the occurrences of each combination.
Sort by Count: Finally, sort these counts in descending order.
Run the following command in your terminal:
awk '{
ip = $1;
match($0, /"[^"]*" ([^ ]*) [^ ]* "([^"]*)"/, arr);
request = arr[1];
ua = arr[2];
url = gensub(/^.*(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS) ([^ ]*).*$/, "\\2", "g", request);
print ip, url, ua;
}' access.log | sort | uniq -c | sort -nr
To explain this command:
awk '{ ... }' access.log: Processes each line of access.log.Inside the awk block:
ip = $1;: Extracts the IP address.match($0, /"[^"]*" ([^ ]*) [^ ]* "([^"]*)"/, arr);: Matches request and User Agent strings using regex.request = arr[1];: Extracts the request part of the match.ua = arr[2];: Extracts the User Agent part of the match.url = gensub(/^.*(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS) ([^ ]*).*$/, "\\2", "g", request);: Extracts the URL from the request.print ip, url, ua;: Prints the IP, URL, and User Agent.The rest of the command:
sort: sorts the lines lexicographically.uniq -c: counts occurrences of each unique line.sort -nr: sorts these counts numerically in descending order.This command will give you the output in the form of:
count IP URL User-Agent
sorted by the count in descending order. If you want the top N results, you can append | head -n N to the command, where N is the number of top entries you want to see.
15 127.0.0.1 /index.html Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
3 192.168.0.1 /about.html Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
...
This way, you get a detailed view of the most frequent requests, including the IP address, URL hit, and User Agent string, sorted by the frequency of occurrence.
Not yet included in a published release.