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' # 预期解析失败
相关资料
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,echo,address,033,resolution,check 来源: https://www.cnblogs.com/Rosaany/p/16579120.html