条件如下:
1、通过ping命令测试192.168.3.1到192.168.3.5之间的所有主机是否在线,
如果在线,就显示"ip is up.",其中的IP要换为真正的IP地址,且以绿色显示;
如果不在线,就显示"ip is down.",其中的IP要换为真正的IP地址,且以红色显示;
要求:分别使用while,until和for(两种形式)循环实现。
方法一:用while实现。
#!/bin/bash IP=1 while [ $IP -le 5 ]; do ping -c 2 -w 2 192.168.3.$IP &>/dev/null STRING=$? # if ping -w 2 -c 2 192.168.3.$IP &>/dev/null;then if [ $STRING -eq 0 ];then echo -e "\033[32;40m192.168.3.$IP is up.\033[0m" else echo -e "\033[31;40m192.168.3.$IP is down.\033[0m" fi let IP=$IP+1 done
或者:
#!/bin/bash # while true; do for I in {1..5};do ping -c 2 -w 2 192.168.3.$I &>/dev/null if [ $? -eq 0 ]; then echo -e "\033[32;40m 192.168.3.$I is UP.\033[0m" else echo -e "\033[31;40m 192.168.3.$I is Down.\033[0m" fi done break done
方法二:用until实现
#!/bin/bash IP=1 until [ $IP -gt 5 ]; do ping -c 2 -w 2 192.168.3.$IP &>/dev/null STRING=$? # if ping -w 2 -c 2 192.168.3.$IP &>/dev/null;then if [ $STRING -eq 0 ];then echo -e "\033[32;40m192.168.3.$IP is up.\033[0m" else echo -e "\033[31;40m192.168.3.$IP is down.\033[0m" fi let IP=$IP+1 done
或者:
#!/bin/bash # until false; do for I in {1..5};do ping -c 2 -w 2 192.168.3.$I &>/dev/null if [ $? -eq 0 ]; then echo -e "\033[32;40m 192.168.3.$I is UP.\033[0m" else echo -e "\033[31;40m 192.168.3.$I is Down.\033[0m" fi done break done
方法三:用for实现
#!/bin/bash # for I in `seq 151 254`; do ping -c 2 -w 2 "192.168.0.$I" &>/dev/null if [ $? -eq 0 ];then echo -e "\033[32;40m192.168.0.$I is up\033[0m" else echo -e "\033[31;40m192.168.0.$I is down\033[0m" fi done
或者:
#!/bin/bash for ((I=1;I<=5;I++ ));do ping -c 2 -w 2 192.168.3.$I &>/dev/null if [ $? -eq 0 ];then echo -e "\033[32;40m192.168.3.$Iis up.\033[0m" else echo -e "\033[31;40m192.168.3.$Iis down.\033[0m" fi done
时间: 2024-10-09 03:52:57