grep the time within given minutes

Mar 26 15:25:11 : jdoe : TTY=pts/2 ; PWD=/home/jdoe ; USER=root ;
    COMMAND=/usr/bin/su -
Mar 26 15:28:52 : jdoe : 3 incorrect password attempts ; TTY=pts/2 ;
    PWD=/home/jdoe ; USER=root ; COMMAND=/usr/bin/su -
Mar 25 12:23:07 : jdoe : TTY=pts/2 ; PWD=/home/jdoe ; USER=root ;
    COMMAND=/usr/bin/su -
Mar 24 11:13:54 : jdoe : TTY=pts/2 ; PWD=/home/jdoe ; USER=root ;
    COMMAND=/usr/bin/su -

I have this log file and need to see who is accessing root.
I need to be notified as soon as a user is accessing root (which is su -).
If instant alerts are not possible, then I can run it with crontab with 5 or 10 minutes of interval.

Can you please advise how to grep the line that has occurred "now", 5 minutes ago, or 10 minutes ago?

Each access has 2 lines as shown above.

Thank you.

:confused:

Why not just watch the logfile as it's being written with tail -f ?

tail -f /path/to/logfile | awk '/TTY/ && /USER=root/ { print; getline ; print }'

I need to get it via e-mail, so tail -f will not work for me on this...

What's your system?

I am on AIX 6.1.
Please advise.

You don't have much in the way of nice date-formatting functions on AIX, but hopefully you have Perl:

# Get the current time, minus five minutes in MM DD HH MM SS
DATE=$(perl -e 'use POSIX qw(strftime);  print strftime "%m %d %H %M %S\n", localtime(time()+$ARGV[0]);' -- -300 )

Then I'll use awk to turn the Mon Day HH:MM:SS times into "MM DD HH MM SS" times, which can be compared with simple < > for order since they sort alphabetically:

# Get the time as of 5 minutes ago, i.e. time+(-300 seconds)
DATE=$(perl -e 'use POSIX qw(strftime);  print strftime "%m %d %H %M %S\n", localtime(time()+$ARGV[0]);' -- -300 )

awk -v DATE="$DATE" 'BEGIN {
        split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", M);
        for(X in M) MON[M[X]]=X; }

{ CMP="" }

# Does the line start with a month?  Convert the date into something
# we can compare.
MON[$1] {
        split($3, H, ":");
        # Turn the date into MM DD HH MM SS, since that can be
        # sorted alphabetically on < > etc.
        CMP=sprintf("%02d %02d %s %s %s", MON[$1], $2, H[1], H[2], H[3]);
}

# If we found a date on the line, and it's greater than our
# start point, print this line and the next one
CMP && (CMP >= DATE) { print ; getline ; print }' logfile
1 Like

Thank you! It works GREAT!!