bash計時器的實現案例:檢查並記錄網絡穩定性的腳本

bash的幫助中提到SECONDS系統變量:

SECONDS Each  time this parameter is referenced, the number of seconds since shell invocation is returned.  If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned.  If SECONDS is unset, it loses its special properties, even if it is subsequently reset.


我們在程序執行期間,檢查這個變量,即可實現記時的功能。


本例是用來每隔一個固定時間,ping一個IP,出現故障時記錄下來的腳本。

#!/bin/bash 
#set -o errexit

export SCRIPT=$0
SID=$PPID
usage(){
	echo -e "Usage:"
	echo -e "\tbash $0 [OPTs]"
	echo -e "\t-W|--timeout\t\t<M>"
	echo -e "\t-I|--interval\t\t<N>"
	echo -e "\t-i|--ip\t\t\t<A.B.C.D>"
	echo -e "\t-L|--level\t\t<info|error>"
	echo -e "\t-l|--log\t\t</tmp/${SCRIPT}-${SID}.log>"
	echo -e "\t-h\t\t\tPrint this info"
	echo -e "Example:"
	echo -e "\tbash $0 -W 1 -I 3 -i 127.0.0.1 -L error -log /tmp/${SCRIPT}-${SID}.log"
	echo -e "\tbash $0"
	exit 255
}

[ $# -eq 4 ] && usage
# 默認參數
LOGFILE="/tmp/${SCRIPT}-${SID}.log"
touch $LOGFILE
TIMEOUT=1
INTERVAL=10
LEVEL=info
IP=127.0.0.1
MyIP=$(ip addr sh eth0 |awk '/^[\ ]*inet /{split($2,IP,"/");printf IP[1]}')
# 參數獲取
TEMP=$(getopt -o W:I:i:L:l:h --long timeout:,interval:,ip:,level:,log:,help -- "$@")
[ $? != 0 ] && usage
eval set -- "$TEMP" 


# 參數處理
while true; do
	case "$1" in
		-W|--timeout) TIMEOUT=$2; shift 2;;
		-I|--interval) INTERVAL=$2; shift 2;;
		-i|--ip) IP=$2; shift 2;;
		-L|--level) LEVEL=$2; shift 2;;
		-l|--log) LOGFILE=$2; shift 2;;
		-h|--help) usage; shift;;
		--) shift; break ;;
	esac
done


[ "$IP" = "" ] && usage
adjust(){
	return $((SECONDS%INTERVAL))
}

pinger(){
	ping $1 -W $TIMEOUT -c 1 | tail -1 |awk -F/ '{print $(NF-1)}' 2>/dev/null  
}	

logger(){
	echo -e "$(date +%F" "%T)\t""$@"	
}

trapper(){
	trap "logger \"EXIT($SID)\t$MyIP -> $IP\" >> $LOGFILE && exit 0"  1 2 9 15 
}

trapper
logger "START($SID)\t$MyIP -> $IP" >> $LOGFILE 
while true
do
	if adjust; then
		unset t 
		t=$(pinger $IP)
		if [ "$t" = "" ]; then
			logger "ERROR($SID)\t$MyIP -> $IP ${TIMEOUT}(S)" >> $LOGFILE &
		else
			[ "$LEVEL" = "erorr" ] || logger "INFO($SID)\t$MyIP -> $IP ${t}(ms)" >> $LOGFILE &
		fi
		sleep 1
	fi
	sleep 0.1
done

執行

bash pinger.sh -W 1 -I 2 -i a.b.c &

執行結果如下:

# tail -f -n 10 /tmp/bash-26729.log 

2015-04-28 17:24:50 START(26729)192.168.202.2 -> a.b.c

2015-04-28 17:24:50 INFO(26729)192.168.202.2 -> a.b.c 0.630(ms)

2015-04-28 17:24:52 INFO(26729)192.168.202.2 -> a.b.c 0.575(ms)

2015-04-28 17:24:54 INFO(26729)192.168.202.2 -> a.b.c 0.875(ms)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章