zl程序教程

您现在的位置是:首页 >  系统

当前栏目

Linux 使用Shell脚本实现测试网络中哪些服务器可以ping通

Linux服务器测试网络shell 实现 脚本 可以
2023-09-14 09:02:05 时间

编写脚本,使用for和while分别实现192.168.0.0/24网段内,地址是否能够ping通,若ping通则输出"success!",若ping不通则输出"fail!"

1 for循环

数字部分在for循环中常见的几种方法:

1. for i in {1..10};do echo $i ;done
2. for i in 1 2 3 4 5 6 7;do echo $i ;done
3. for i in `seq 10`;do echo $i ;done
4. for((i=1;i<10;i++));do echo $i ;done
#!/bin/bash
. /etc/init.d/functions
IP=10.192.225.
for i in {1..254};do
        if [[ ! `ping $IP$i -c 1|grep Destination`  =~ .*Destination.* ]]  ;then
                success ;
                echo "$IP$i地址可以被ping通!"
        else failure
        	echo "$IP$i地址无法被ping通!"
	fi
done

在这里插入图片描述

2 while循环

2.1 while的第一种做法

在while 头上设置好条件,当不满足条件则退出

#!/bin/bash
. /etc/init.d/functions
IP=192.168.31.
i=1
while [ $i -lt 100 ]
do
        if [[ `ping $IP$i -c 1|grep -o ttl`  =~ "ttl" ]];then
                success;
                echo "$IP$i地址可以被ping通!"
        else
                failure
                echo "$IP$i地址无法被ping通!"
        fi
        let i+=1
done

在这里插入图片描述

2.2 while第二种做法

使用while True的方法,但必须有退出条件,当满足退出条件则break出循环

#!/bin/bash
. /etc/init.d/functions
IP=192.168.31.
i=1
while [ 1 ]
do
	if [[ `ping $IP$i -c 1|grep -o ttl`  =~ "ttl" ]];then
		success;
		echo "$IP$i地址可以被ping通!"
	else
		failure
		echo "$IP$i地址无法被ping通!"
	fi
       [ $i -lt 10 ] && let i+=1||break

done

在这里插入图片描述