脚本实现目的:
通过脚本检测相应的文件是否发生改变。
脚本思路:
使用文件的md5值作为检测依据,若文件发生变化,则记录日志,并备份发生改变的文件。
通过配置文件的方式指定文件传递给脚本,以方便批量部署。
脚本内容:
#!/bin/bash#use for check file change#create in 2013-06-07#Last modify is 2014-04-09source ~/.bash_profile &> /dev/nullcd /tol/script/ls /tol/script/logs &> /dev/null || /bin/mkdir -p /tol/script/logsbakdir=/tol/backup/conf_bakls $bakdir &> /dev/null || /bin/mkdir -p $bakdirdt2=`date +"%F"`log="/tol/script/logs/md5_check-$dt2.log"host=`/sbin/ifconfig |grep "inet addr"|cut -d ':' -f2 |awk '{print $1}'|head -1`conf=/tol/script/md5_check.confoldlist=/tol/script/md5_check.oldnewlist=/tol/script/md5_check.newif test ! -f $conf ; then echo "the $conf does not exist" exit 0 elseif test ! -f $oldlist ; then for f in `cat $conf` do /usr/bin/md5sum $f >> $oldlist done #/usr/bin/chattr +i $oldlistelse for f in `cat $conf` do dt=`date +"%F_%T"` /usr/bin/md5sum $f > $newlist old=`cat $oldlist |/bin/grep "$f" |/bin/awk '{print $1}'` new=`cat $newlist |/bin/grep "$f" |/bin/awk '{print $1}'` if test -z "$old" ; then #/usr/bin/chattr -i $oldlist /usr/bin/md5sum $f >> $oldlist #/usr/bin/chattr +i $oldlist #exit 0 else if test "$new" != "$old" ; then tar -jpcf $bakdir/`basename $f`_$dt.bz2 $f &> /dev/null sed -i "s/$old/$new/g" $oldlist echo "$dt the $host $f was changed" >> $log echo "#" >> $log echo "The $f changed time:" >> $log /bin/ls -l --time-style=long-iso $f >> $log echo "#" >> $log echo "The $host last 3 login user:" >> $log /usr/bin/last |/usr/bin/head -3 >> $log echo "#" >> $log #echo "$dt the $host $f was changed" |mail -s "check $host $f" jiank #else # echo "$dt the $host $f is normal" >> $log fi fi donefifi
脚本配置文件:
/etc/passwd
/etc/group
/etc/shadow
md5sum命令的常见用法:
md5sum 文件名#查看某一个文件的MD5值
md5sum *.html#查看当前目录下某一类型文件的MD5值,这里是html
md5sum *#查看当前目录下所有文件的MD5值
md5sum -c 保存MD5值的文件名#根据保存MD5值的文件里的内容比对文件是否有变化
find /dir -type f -print0|xargs -0 md5sum > ~/md5 #查看某个目录下所有文件的MD5值