开发者

Shell script for parsing log file

I'm writing a shell script to parse thr开发者_C百科ough log file and pull out all instances where sudo succeeded and/or failed. I'm realizing now that this probably would've been easier with shell's equivalent of regex, but I didn't want to take the time to dig around (and now I'm paying the price). Anyway:

sudobool=0
sudoCount=0

for i in `cat /var/log/auth.log`;
do
    for word in $i;
    do
        if $word == "sudo:"
        then
            echo "sudo found"
            sudobool=1;
            sudoCount=`expr $sudoCount + 1`;
        fi
    done

    sudobool=0;

done


echo "There were " $sudoCount " attempts to use sudo, " $sudoFailCount " of which failed."

So, my understanding of the code I've written: read auth.log and split it up line by line, which are stored in i. Each word in i is checked to see if it is sudo:, if it is, we flip the bool and increment. Once we've finished parsing the line, reset the bool and move to the next line.

However, judging by my output, the shell is trying to execute the individual words of the log file, typically returning '$word : not found'.


why don't you use grep for this?

grep sudo /var/log/auth.log

if you want a count pipe it to wc -l

grep sudo /var/log/auth.log | wc -l

or still better use -c option to grep, which prints how many lines were found containing sudo

grep -c sudo /var/log/auth.log

or maybe I am missing something simple here?
EDIT: I saw $sudoFailCount after scrolling, do you want to count how many failed attempts were made to use sudo ?? You have not defined any value for $sudoFailCount in your script, so it will print nothing. Also you are missing the test brackets [[ ]] around your if condition checking


Expanding on Sudhi's answer, here's a one-liner:

$ echo "There were $(grep -c ' sudo: ' /var/log/auth.log) attempts to use sudo, $(grep -c ' sudo: .*authentication failure' /var/log/auth.log) of which failed."
There were 17 attempts to use sudo, 1 of which failed.


Your error message arises from a lack of syntax in your if statement: you need to put the condition in [[brackets]]

Using the pattern matching in bash:

#!/bin/bash
sudoCount=0
while read line; do
    sudoBool=0
    if [[ "$line" = *sudo:* ]]; then
        sudoBool=1
        (( sudoCount++ ))
        # do something with sudobool ?
    fi
done < /var/log/auth.log
echo "There were $sudoCount attempts to use sudo."

I'm not initimately familiar with the auth.log -- what is the pattern to determine success or failure?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜