#Set the variable which equal to zero prev_count=0 count=$(grep -i "`date --date='yesterday' '+%b %e'`" /var/log/secure | egrep -wi 'useradd' | wc -l)
if [ "$prev_count" -lt "$count" ] ; then # Send a mail to given email id when errors found in log SUBJECT="ATTENTION: New User Account is created on server : `date --date='yesterday' '+%b %e'`" # This is a temp file, which is created to store the email message. MESSAGE="/tmp/new-user-logs.txt" TO="2daygeek@gmail.com" echo"Hostname: `hostname`" >> $MESSAGE echo -e "\n" >> $MESSAGE echo"The New User Details are below." >> $MESSAGE echo"+------------------------------+" >> $MESSAGE grep -i "`date --date='yesterday' '+%b %e'`" /var/log/secure | egrep -wi 'useradd' | grep -v 'failed adding'| awk '{print $4,$8}' | uniq | sed 's/,/ /' >> $MESSAGE echo"+------------------------------+" >> $MESSAGE mail -s "$SUBJECT""$TO" < $MESSAGE rm$MESSAGE fi
给 new-user.sh 添加可执行权限。
1
$ chmod +x /opt/scripts/new-user.sh
最后添加一个 cron 任务来自动化执行它。它会在每天 7 点运行。
1 2 3
# crontab -e
07 * * * /bin/bash /opt/scripts/new-user.sh
注意:你将在每天 7 点收到一封邮件提醒,但这是昨天的日志。
你将会看到类似下面的邮件提醒。
1 2 3 4 5 6 7 8 9
# cat /tmp/logs.txt
Hostname: 2g.server10.com
The New User Details are below. +------------------------------+ 2g.server10.com name=magesh 2g.server10.com name=daygeek +------------------------------+