要实现用shell/ target=_blank class=infotextkey>shell脚本检测多台机器的cpu使用情况,需要做到:
1,定义机器列表文件hostlists。
2,使用saru.sh自动rlogin到各机器上使用sar -u 60 180(间隔和次数选项可自定义)。
3,把各机器的统计结果各自存放。
4,从各机器的统计结果中取出最后的平均值放入简明日志中
注:以下脚本在HP-UX上通过,hp-ux的bash为/sbin/sh,sun-solaris为/sbin/bash。
其它系统为/bin/bash或/bin/sh/
# cat ./saru.sh
#!/sbin/sh
#define logfile&hostlists
hostlists="/etc/chk/hosts.sar-u.lst"
if [ ! -d /etc/chk/log/`date +%Y%m%d` ];then
mkdir -p /etc/chk/log/`date +%Y%m%d`
fi
logfile=/etc/chk/log/`date +%Y%m%d`/sar-u.log
cat /dev/null >$logfile
#monitor the check-logfile in-real-time
#tail -f $logfile &
#define shell-script's option
if [ "$1" = "" ]
then
intv=60
else
intv=$1
fi
if [ "$2" = "" ]
then
counts=180
else
counts=$2
fi
if [ "$3" = "" ]
then
sleeptimes=60
else
sleeptimes=$3
fi
#main shell-script begin
for i in `cat $hostlists | grep -v #`
do
#clear old-checking-log of today
if [ -f $logfile.$i ]
then
cat /dev/null >$logfile.$i
else
touch $logfile.$i
fi
#begin to check item
echo "check $i"
(sleep 10;echo "sar -u $intv $counts &";sleep $(((intv+intv/10+1)*(counts+10)));) | rlogin $i | egrep "^$i|Average|:|idle" >>$logfile.$i &
done
#monitor if check-log-file has been finished
while :;do
working="done"
for i in `cat $hostlists | grep -v #`
do
if [ ! -f $logfile.$i ];then
working="nofile"
elif [ `ls -l $logfile.$i | linuxjishu/13830.html target=_blank class=infotextkey>awk '{print $5}'` -eq 0 ];then
working="zero"
fi
done
if [ "$working" = "done" ];then
break
fi
sleep $sleeptimes
done
#get brief-result from detail check-log-file for per-host
sleep 5
for i in `cat $hostlists | grep -v #`
do
cat $logfile.$i | egrep "sar|Average|idle" >>$logfile
echo >>$logfile
done
#exit and kill the tail-f process
echo ""
echo "the host in $hostlists has not been checked:"
echo `cat $hostlists | grep #`
echo "all the sar-d brief-result has been saved to $logfile."
echo "for detail result,please watch $logfile.hostname file."
#kill `ps -f -u root | grep "tail -f $logfile" | awk '{print $2}'` >/dev/null
exit 0
调用方法: