作用:通过ping工作实时监控多台主机
实现:多进程后台运行,并分区域显示
使用:将欲监控的主机作为参数
演示:
代码专区:
#/bin/bash # LY # ------------------ # Copyright 2016.04.14 LingYi ([email protected]) QQ:1519952564 # "monitor hosts by batch ping in the background" all_sum=0 success_sum=0 failed_sum=0 failed_percent=0 pids_arry=() signs_arry=() ips_arry=([email protected]) line_start=5 #显示间隔(行) line_interval=1 #后台运行函数,实现ping操作以及在规定区域打印统计信息 exec_func() { local stop_exec=false trap ‘stop_exec=true‘ $3 while ! $stop_exec; do ping -c 1 -W 2 $1 &>/dev/null && (( success_sum+=1 )) || (( failed_sum+=1 )) (( all_sum+=1 )) failed_percent=$( echo "scale=2;${failed_sum}/${all_sum}*100" | bc ) echo -ne "\033[$2;1H" printf " %-16s%-10s%-10s%-10s%-10s" $1 $all_sum $success_sum $failed_sum "${failed_percent}%" usleep 1$((RANDOM%5))00000 done } #捕捉信号(一般ctrl+c),并忽略 trap ‘ ‘ 2 #隐藏鼠标 tput civis clear printf "\n\t\t%s\n" ‘Ping Monitor [ "Q" to Exit ! ]‘ printf "%57s\n" ‘ ‘ | tr ‘ ‘ ‘=‘ printf " %-16s%-10s%-10s%-10s%-10s\n" IP Sum Suc Fail Perc #循环监控主机,并记录后台进程的进程号,以便运行结束后禁止其运行 for(( index=0; index<${#ips_arry[@]}; index++ )); do sign=$((RANDOM%20+10)) (( line_start+=line_interval )) exec_func ${ips_arry[index]} $line_start $sign & pids_arry=( ${pids_arry[@]} $! ) signs_arry=( ${signs_arry[@]} $sign ) usleep $((RANDOM%5+6))00000 done #接收用户通过“q”键 终止脚本运行 while :; do read -s -n 1 user_input if [[ $user_input == ‘q‘ ]]; then for ((index=0; index<${#ips_arry[@]}; index++ )) do kill -${signs_arry[index]} ${pids_arry[index]} &>/dev/null done tput cnorm sleep 1 echo -ne "\033[$line_start;1H" echo exit fi done
时间: 2024-10-12 08:34:50