Skip to content

Instantly share code, notes, and snippets.

@olund
Created September 14, 2015 16:05
Show Gist options
  • Save olund/a876f5456deb02a5d121 to your computer and use it in GitHub Desktop.
Save olund/a876f5456deb02a5d121 to your computer and use it in GitHub Desktop.
#!/bin/bash
if [ "$#" -le 0 ]; then
echo "Usage $0 [-n N] (-c|-2|-r|-F|-t) <filename>"
exit 2
fi
FILE="${@: -1}" #File is the last argument
nrOfResult=0
#-r FILE exist and read permission.
if [ ! -r $FILE ]; then
echo "File does not exist, using stdin\n"
cat <&0 > "$FILE"
#exit 2
fi
function mostConnectionAttemps() {
# 1. Get all ips from file
# 2. Sort
# 3. Uniq --count (prefix lines by the number of occurrences)
# 4. Sort numeric and reverse the result
# 5. Change place of the arguments of the result of sort.
local VAR=`awk '{ print $1 }' $FILE | sort | uniq --count | sort -nr | awk '{ print $2, "\011", $1}'`
myPrint "$VAR" "<IP><NrOfResult>" "$1"
}
function mostSuccessfulAttemps() {
local VAR=`awk {'print $9, $1 '} $FILE | grep -E '^2..|^3..' | sort | uniq --count | sort -rn | awk {'print $3, "\011", $1'}`
myPrint "$VAR" "<ip><nrOfRequests>" "$1"
}
function mostBadRequest() {
local VAR=`awk {'print $9, $1 '} $FILE | grep -E '^4..|^5..' | sort | uniq --count | sort -rn | awk {'print $2, "\011", $3'}`
myPrint "$VAR" "<Code><Ip>" "$1"
}
function mostCommonResultCode() {
# 1. Get all status codes
# 2. Sort
# 3. Uniq --count
# 4. Sort numeric and reverse
# 5. Change order of print by using awk.
local VAR=`awk {'print $9, $1'} $FILE | sort | uniq --count | sort -rn | awk {'print $2, "\11", $3'}`
myPrint "$VAR" "<StatusCode><ip>" "$1"
}
function countBytesByIp() {
# local VAR=`awk {'if ($10 !="-")print $10, $1'} $FILE | sort -k2,2 | awk '{arr[$2]+=$1} END { for(i in arr) { print i, "\011", arr[i]}}' | sort -rnk2,2`
# myPrint "$VAR" "<ip><bytes>" "$1"
# Get all ips with bytes
# Group all ips and perform
# sum += byte
local VAR=`awk {'if ($10 !="-")print $10, $1'} $FILE | sort -k2,2`
local counter=0
for line in $VAR; do
#local ip=`echo $line | cut -d ' ' -f 1`
#echo $ip
# cat $line | cut -d ' ' -f1 $ip
ip=${line%% *}
printf "%s\n" "$ip"
let counter+=1;
done
}
# $1 $VAR
# $2 Description
# $3 N - Number of results.
function myPrint() {
# If we have -N set, use head to limit the results
if [ "$3" -gt 0 ]; then
echo "$2"
printf "$1" | head -n "$3"
else
printf "$2\n$1"
fi
}
while getopts :n:c2rFt option
do
case $option in
n)
nrOfResult=$OPTARG
;;
c)
# call function with argument (N)
mostConnectionAttemps $nrOfResult
;;
2)
mostSuccessfulAttemps $nrOfResult
;;
r)
mostCommonResultCode $nrOfResult
;;
F)
mostBadRequest $nrOfResult
;;
t)
countBytesByIp $nrOfResult
;;
#*)
# echo "Not a valid argument"
# ;;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment