Shell使用ping检查主机的可用性

2022/8/13 5:24:48

本文主要是介绍Shell使用ping检查主机的可用性,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

写一个脚本,检查网络设备是否在线或者解析地址成功,这里尝试使用ping命令

实现

check_address_resolution.sh

#!/bin/bash

RED="\033[31m"      # Error message
GREEN="\033[32m"    # Success message
YELLOW="\033[33m"   # Warning message
BLUE="\033[36m"     # Info message
PLAIN='\033[0m'

colorEcho() {
    echo -en "${1}${@:2}${PLAIN}"
}

slogon() {
	echo ""
    echo "#########################################################"
    echo -e "#\t${GREEN}${@:1}${PLAIN}\t"
    echo "#########################################################"
}

<<COMMENT
	获取日期和时间
COMMENT
function print_debug_time {
	colorEcho $GREEN `date +%Y-%m-%d` `date +%H:%M:%S`;
	echo -n " ";
}

<<COMMENT
	检查联网、地址解析状况
COMMENT
########################## 看下面 ######################
function check_address_resolution {
	print_debug_time;
	command="${@}";
	if [[ $command == "" ]]; then
		echo "no found args"
	fi

	ping -c 2 $command >/dev/null 2>&1;

	if [[ $? == 0 ]]; then
	# 0 表示主机可达;1 表示无回复;2 表示无法访问
		colorEcho $GREEN "ping $command is success\n"

	else
		colorEcho $RED "ping $command is fail!\n"
	fi
}

slogon 检查联网、地址解析状况
check_address_resolution '192.168.1.1' 		# 预期ping通
check_address_resolution '192.168.1.2' 		# 预期ping不通
check_address_resolution '114.114.114.114'   	# 预期ping通
check_address_resolution 'baidu.com'   		# 预期解析失败

image

相关资料

https://stackoverflow.com/questions/18123211/checking-host-availability-by-using-ping-in-bash-scripts
https://stackoverflow.com/questions/921398/exit-status-of-ping-command



这篇关于Shell使用ping检查主机的可用性的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程