檢測範圍 Server IP 是否 Ping 回應 – bash script

2015-11-06 Bash

有時候會需要檢測範圍性的主機是否有在線上,所以寫了一隻簡易的 Ping Server 的 bash script

 

Pingip.sh

#!/bin/bash
# Program:
# 	Use Ping command to check NETWORK's Server state.
# 
# Copyright (c) 2015 Scott liao

SCRIPT=${0##*/}

NETWORK="192.168.50"
IP_START="$1"
IP_END="$2"

# --- start SCRIPT ---
trap 'stop' SIGUSR1 SIGINT SIGHUP SIGQUIT SIGTERM SIGSTOP

stop() {
	echo -e "\nStop ${SCRIPT} script ...."
	exit 0
}

help() {
	echo -e "
Usage: $SCRIPT [IP_START] [IP_END]

Example:
	$SCRIPT 1 254
	$SCRIPT 100 200
"
}


if [[ ! -z ${IP_START} && ! -z ${IP_END} ]]; then
	echo -e "\nStart ${SCRIPT} Scanner Server ...."

	for opt in $(seq ${IP_START} ${IP_END})
	do 
		
		ping -c 1 -W 1 ${NETWORK}.${opt} &> /dev/null && result=0 || result=1

		if [ "${result}" == 0 ]; then
			echo "Server ${NETWORK}.${opt} is UP."
		else
			echo "Server ${NETWORK}.${opt} is DOWN."
		fi
	done

else
	help

fi

 

script 中加入了 trap 來讓 script 執行中可以 Ctrl + C 取消執行,如果沒有加入 trap 就會持續執行到 script 結束

 

在環境變數中,你必須指定 network 來代表你的網段

 

使用方式:指定你要的範圍 IP 10 ~ 100

$ ./Pingip.sh 10 100

Start Pingip.sh Scanner Server ....
Server 192.168.0.10 is UP.
Server 192.168.0.11 is UP.
Server 192.168.0.12 is UP.
...
...
Server 192.168.0.10 is DOWN.

 

 

給 Mr. 沙先生一點建議

彙整

分類

展開全部 | 收合全部

License

訂閱 Mr. 沙先生 的文章

輸入你的 email 用於訂閱