linux 批量ping检测

本文介绍了一个使用Bash编写的脚本,该脚本能够从本地配置文件中读取IP地址列表,并对这些IP地址进行连续扫描。如果所有IP地址在多次尝试后仍无法响应,则会触发特定的任务执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从本地文件中加载ip地址清单,全ip扫描,如果所有ip ping失败多次,执行某个任务:

#! /bin/bash

#ping module:testPing ipAddr
testPing(){
	local ipAddr=$1

	ping -w 1 -c 2 $ipAddr > /dev/null
	local result=$?
	if [ $result -eq 0 ]
	then
		echo "1"
	else
		echo "0"
	fi
}

#ip list from local conf
#testPing localConf
testFromConf(){
	local localConf="$1"
	for ipAddr in `cat $localConf`
	
	do
		local result=`testPing $ipAddr`
		if [ $result -eq "1" ]
		then
			#echo $ipAddr":true"
			#ping one addr success
			echo "1"
			return
		#else
			#echo $ipAddr":false"
		fi
	done
	
	#all addrs ping failed
	echo "0";
}

#ping loop
#testPingLoop maxCount conf
testPingLoop(){
	local maxCount=$1
	local conf=$2
	
	for((i=0;i<$maxCount;++i))
	do
		local result=`testFromConf $conf`
		if [ $result -eq "1" ]
		then
			#some task sucess,exit this ping loop
			echo "1"
			return
		#else
			#
		fi
		
	done

	#has retry maxCount,failed
	echo "0"
}

taskIfFailed(){
	echo "need reboot?"
}

pingTask(){
	local maxCount=$1
	local conf=$2

	while true
	do
		local result=`testPingLoop $maxCount $conf`
		if [ $result -eq "1" ]
		then
			#if success, sleep some seconds
			echo "success"
			sleep 1
		else
			taskIfFailed
		fi
	done
}

main(){
	#testPing "127.0.0.1"
	#testPing "172.1.1.1"
	#testFromConf "pingtest.txt"
	pingTask 1 "pingtest.txt"
}

main



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值