14 August, 2007

HowTo check files integrity via shell script

In order to control integrity of files on my fileserver I've created special script.
It walks around filesystem (in the given directory) and calculates checksums for files or checks their.
If the file has been changed after last check the warning message will be displayed.



Script:


xqx_uintegra.sh

#!/bin/bash

#Checks files integrity via md5sum utility.
#
#For removal of all *.md5 files, execute: find -name "*.md5" -exec rm {} \;
#Usage:
# xqx_uintegra.sh "/path/to/directory"


DATE=`date +%Y.%m.%d_%H.%M.%S.%N`
LOG=~/`basename $0`-$DATE.log
touch $LOG

if test ! -w "$LOG"; then
LOG=/dev/stdout
fi

SHIFT=$[`tput cols`-10]
MOVE="\\033["$SHIFT"G"
DEFAULT="\\033[0;39m"
RED="\\033[1;31m"
GREEN="\\033[1;32m"
YELLOW="\\033[1;33m"
BLUE="\\033[1;34m"

logError_end() {
echo -e "$MOVE$RED$1$DEFAULT"
echo -e \\t$1 >>$LOG
}

logOk_end() {
echo -e "$MOVE$GREEN$1$DEFAULT"
echo -e \\t$1 >>$LOG
}

logWarning_end() {
echo -e "$MOVE$YELLOW$1$DEFAULT"
echo -e \\t$1 >>$LOG
}

checkSum() {
#$1=file
echo -en CheckSum:\\t$1
echo -en CheckSum:\\t$1 >>$LOG
file=`basename $1`
dir=`dirname $1`
(cd $dir && md5sum -c -- $file >/dev/null 2>&1 && logOk_end OK || logError_end ERROR)
}

calcSum() {
#$1=file
echo -en CalcSum:\\t$1
echo -en CalcSum:\\t$1 >>$LOG
file=`basename $1`
dir=`dirname $1`
(cd $dir && md5sum -b -- $file >$file.md5 2>/dev/null && logWarning_end CALCULATED || logError_end ERROR)
}


fin_process() {
while read; do
#echo $REPLY
if test -n "`echo $REPLY | grep '\.md5$'`"; then
checkSum $REPLY
else
if test ! -f "$REPLY.md5"; then
calcSum $REPLY
fi
fi
done
}


find $1 -type f | fin_process;
echo
echo -e "\\033[1;31m"
cat $LOG |grep ERROR
echo -e "\\033[0;39m"


This script works in Linux systems and under Cygwin environment.

Examples of usages:
In the Windows+Cygwin:
bash xqx_uintegra.sh E:/Temp/sun

In the Linux:
xqx_uintegra.sh /home/fileserver

No comments: