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

发布时间 2023-10-07 14:22:57作者: 小糊涂90

for方法:


[14:20:07 root@centos8 ~]#cat ping_for.sh
#!/bin/bash

#================================================================
#   Copyright (C) 2021 IEucd Inc. All rights reserved.
#
#   文件名称:ping_for.sh
#   创 建 者:TanLiang
#   创建日期:2021年10月17日
#   描   述:This is a test file
#
#================================================================

#!/bin/bash
NETID=192.168.0
for ip in {1..254};do
      {
              if /bin/ping -c1 -w1 $NETID.$ip >/dev/null;then
                      echo "ping $NETID.$ip is success!"
              else
                      echo "ping $NETID.$ip is fail!"
              fi
      }&
done
wait

while方法:


[14:43:33 root@centos8 ~]#cat ping_while.sh
#!/bin/bash

#================================================================
#   Copyright (C) 2021 IEucd Inc. All rights reserved.
#
#   文件名称:ping_for.sh
#   创 建 者:TanLiang
#   创建日期:2021年10月17日
#   描   述:This is a test file
#
#================================================================

#!/bin/bash
NETID=192.168.0
declare -i ip=1
      while [ $ip -lt 255 ];do
      {
      /bin/ping -c1 -w1 $NETID.$ip &>/dev/null
      if [ $? -eq 0 ];then
              echo "ping $NETID.$ip is success!"

      else
              echo "ping $NETID.$ip is fail!"
      fi
      }&
      let ip++
done
wait

[14:46:59 root@centos8 ~]#bash ping_for.sh |sort -n -t"." -k 4