分类: LINUX
2008-11-04 02:45:45
写了两个脚本,一个是随机ping局域网的存活主机,一个是ping广域网网关,用crontab定时执行.
主要学习了随机数生成,并吸取了没有路径致使脚本不正常的教训.开始ping局域网脚本总提示找IP失败,而手工执行总是成功,查了很久才知道不应该用arp,应用/usr/sbin/arp,也就是很多命令都应该注意路径,想来应该是在/usr下的吧
ping.sh的内容:
#!/bin/bash
# Ping random LAN IP
PINGFILE=/root/ping.txt
FILEUSER=win
FILEGROUP=win
PINGCOUNT=180
MAX_FIND_IP_COUNT=10
if [ ! -f $PINGFILE ];then
touch $PINGFILE
chown $FILEUSER:$FILEGROUP $PINGFILE
fi
IP=
GETIPCOUNT=0
until [ ! -z $IP ]
do
IPNUM=`/usr/sbin/arp -n|grep -v incomplete|grep 192.168.0|wc -l`
RANDNUM=`expr $RANDOM % $IPNUM + 1`
IP=`/usr/sbin/arp -n|grep -v incomplete|grep -e '^192\.168\.0\.'|awk '{print \$1}'|head -n $RANDNUM|tail -n 1`
let GETIPCOUNT=GETIPCOUNT+1
if (( GETIPCOUNT > MAX_FIND_IP_COUNT ));then
echo -e "\nNow is `date \"+%F %T\"`,Find IP failure!!!\n" >> $PINGFILE
exit
fi
if [ ! -z $IP ];then
echo -e "\nNow is `date \"+%F %T\"`,Will ping $IP,Count=$PINGCOUNT......\n" >> $PINGFILE
fi
done
ping -c $PINGCOUNT -q $IP >> $PINGFILE
ping1.sh的内容:
#!/bin/bash
# Ping Gateway
PINGFILE=/www/win/game/ghost/ping1.txt
FILEUSER=win
FILEGROUP=win
PINGCOUNT=180
IP=123.12.13.1
if [ ! -f $PINGFILE ];then
touch $PINGFILE
chown $FILEUSER:$FILEGROUP $PINGFILE
fi
echo -e "\nNow is `date \"+%F %T\"`,Will ping $IP,Count=$PINGCOUNT......\n" >> $PINGFILE
ping -c $PINGCOUNT -q $IP >> $PINGFILE
crontab -e 加入下面的内容,每10分钟执行一次
# m h dom mon dow command
*/10 * * * * /root/sh/ping.sh
*/10 * * * * /root/sh/ping1.sh