当前位置: > shell编程 >

ping所有主机的shell脚本(图文)

时间:2014-09-30 22:15来源:linux.it.net.cn 作者:it

用shell脚本实现ping网段中的所有主机,代码如下:
 

复制代码代码示例:
#!/bin/sh
# ping all host
# find from /etc/hosts for host info,and filter IP address
cat /etc/hosts | grep -v ^# |grep -v ^$ | while read LINE
do
   for M in `awk '{print $1}'`
    do
      ping -c1 $M
   done
done

以上脚本比较简单,对在/etc/hosts/中配置的主机,进行单次ping检测。

代码说明:
1,cat file是显示文件.
2,grep进行文本过滤,-v选项显示不包含匹配文本的行,^#表示以#开头的行。
  grep -v ^# 表示不显示以#开头的行.
  grep -v ^$ 表示不显示空行.
3,通过管道(|)的方式把前者的输出作为后者的输入,并用while读取只有IP的文本的每一行。
4,awk命令输出该IP串。
注意,`awk '{print $1}'`中,最外层是反引号,内层是单引号。
5,for循环遍历每行IP串,进行ping主机的操作。
-c 指定ping的次数,本例中为只ping一次。

调用示例,如下图:
ping主机

对以上脚本进行改进,以实现如下的功能:
1,判断主机状态,输出易于理解的提示信息,比如:
192.168.1.2 is up

192.168.1.3 is down

改进后的脚本如下:
 

复制代码代码示例:
#!/bin/sh
# ping all host
# find from /etc/hosts for host info,and filter IP address
cat /etc/hosts | grep -v ^# |grep -v ^$ | while read LINE
do
   for M in `awk '{print $1}'`
    do
      if ping -w 1 -c 1 $M | grep "100%" >/dev/null  
      then
          echo "$M is down"
      else
          echo "$M is up"
      fi
   done
done

调用示例,如下图:
ping主机

(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容