shell 实现ping检测存活主机(多进程后台实现)

 由于shell脚本没有多线程可以用,所以只能利用多进程的方法来提速了,后期会考虑用高级语言写,

下面介绍我的代码

用到的知识点:

  • bash ./a.sh 和 .  ./a.sh 和 source ./a.sh 和./a.sh 运行脚本区别
    bash  a.sh:系统会创建名为bash进程将a.sh的代码读到进程里直接运行,a.sh文件只需要读权限不需要执行权限
    .  ./a.sh:将a.sh代码读到当前进程里执行,a.sh只需要读权限
    source  a.sh:和. ./a.sh一样
    ./a.sh :a.sh需要执行权限
  • shell执行命令后会得到执行命令的返回值,成功返回0  失败返回非0(一般为1)
    
    [root@server7-128 /etc]# ping 192.168.107.5
    connect: 网络不可达
    [root@server7-128 /etc]# echo $?
    2
    [root@server7-128 /etc]# 
    
    
    
    [root@server7-128 /etc]# ping 192.168.109.1
    PING 192.168.109.1 (192.168.109.1) 56(84) bytes of data.
    64 bytes from 192.168.109.1: icmp_seq=1 ttl=128 time=1.05 ms
    64 bytes from 192.168.109.1: icmp_seq=2 ttl=128 time=0.298 ms
    64 bytes from 192.168.109.1: icmp_seq=3 ttl=128 time=0.258 ms
    ^C
    --- 192.168.109.1 ping statistics ---
    3 packets transmitted, 3 received, 0% packet loss, time 2002ms
    rtt min/avg/max/mdev = 0.258/0.536/1.052/0.365 ms
    [root@server7-128 /etc]# echo $?
    0
    [root@server7-128 /etc]# 
    

                

  •    查看是否是多进程状态输入pstree -p 显示进程id信息,我在进程里写了个输出进程id和sleep 30(方便验证)可自行测试


 

代码部分:

#!/bin/bash

#########################################
# 格式:                                # 
#   该脚本名  *.*.*.1-255               # 
# 例如:                                # 
#   ping.sh 192.168.100.2-100           # 
#                                       # 
# 文件作用:                            # 
#     pings.sh 子进程脚本ping           # 
#     chip.txt 存放存活主机             # 
#     bchip.txt 存放不存在主机          # 
#                                       # 
#                                       # 
#                                       # 
#########################################
echo '
#!/bin/bash

ping -c 1 $1 1>/dev/null 2>/dev/null
if [ $? -eq 0 ];then
       echo "--------------------- 主机存活: $1" >> chip.txt
else
    echo "$1 不存在!" >> bchip.txt
fi
' > pings.sh

##设置ping.sh脚本执行权限,删除记录文件方便二次执行#####
#### chip.txt 存活的ip
####bchip.txt 不存在的ip
chmod u+x pings.sh
rm -f chip.txt bchip.txt >/dev/null 2>&1

#获得起始地址 IP地址的最后一位
a=`echo $1 | awk -F "." '{print $4}' | awk -F "-" '{print $1}'`  
#获得结束地址 IP地址的最后一位
b=`echo $1 | awk -F "." '{print $4}' | awk -F "-" '{print $2'}`  
echo " "

#字符转数字
a1=$((a))
b1=$((b))

#循环创建进程同时去ping多台主机
for ((i=a1;i<=b1;i++))
do
    w=`echo $1 | awk -v name=$i -F "." '{print $1 "." $2 "." $3 "." name}'`
    ./pings.sh $w &
done

猜你喜欢

转载自blog.csdn.net/qq_38228830/article/details/81356984