Hey All,
So what I'm attempting to do is search for a particular string in a log file that appears after a certain time. Pull the usernames from the results and count the number of times each username appears.
What I'm having trouble with is coming up with a way to trigger an email if any of the usernames appear more than a certain number of times.
Here's a simplified snipped of code of what I've done so far.
Code:
#!/bin/bash
checktime () {
while read line; do
# code that checks if the timestamp of each line is after
# a certain time; if it is, echo the line
done
}
# grep logfile for search_string; pass the results to the checktime function.
# use awk to pull usernames from the results and count number of occurrences
# for each user
grep search_string logfile | checktime | awk '{print $9}' sort | uniq -c
This part works. What I'd like to do next is send an email with the usernames and their count if the count exceeds a certain amount. I can come up with ways to do it, but it doesn't seem very efficient/elegant. For example:
Code:
#!/bin/bash
results=""
checktime () {
while read line; do
# code that checks if the timestamp of each line is after
# a certain time; if it is, echo the line
done
}
# print username if it appears more than 50 times in the results
checklogs () {
while read line; do
if [[ $(echo $line | awk '{print $1}') -ge 50 ]]; then
echo $line
fi
done
}
# grep logfile for search_string; pass the results to the checktime function.
# use awk to pull usernames from the results and count number of occurrences
# for each user. pass this to the checklogs function.
results=$(grep search_string logfile | checktime | awk '{print $9}' sort | uniq -c | checklogs
# if $results isn't empty, at least one user exceeded the count. email results.
[[ "$results" != "" ]] && echo $results | /bin/mail -s "results" addy@domain.com
This seems to work (though I'm left with the formatting problem when echo'ing $results to an email), but I'm looking for suggestions on how to better do it.