今天复习笔记的时候看到有记录一篇是关于检查主机存活列表,并以HTML的形式输出的shell脚本,在centos上试了一下,发现有一些错误,遂通过一番整改,bug修复,代码如下:

 
  
  1. #!/bin/bash 
  2. shopt -s -o nounset 
  3. HostList=${1:?'please inpute host ip address!'} 
  4. [ ! -f $HostList ] && echo 'the file not exist' && exit 1 
  5. Date=$(date +"%Y%m%d%H%M") 
  6. Date_for_man=$(date +"%Y-%m-%d %Hhour %M minutes") 
  7. #the counts of ping 
  8. pno=2 
  9. #path file to save 
  10. padir="/var/www/html/pa" 
  11. pahtml="$padir/index.html" 
  12. pahtml_now="$padir/pa-$Date.html" 
  13.  
  14. #functions 
  15.  
  16. function html_head(){ 
  17.   [ ! -e $padir ] && mkdir -p $padir 
  18.   cat >$pahtml_now<<HEAD 
  19.   <html> 
  20.   <head> 
  21.   <title>ping alive check result</title> 
  22.   <meta HTTP-EQUIV="Refresh" CONTENT="900"> 
  23.   <meta HTTP-EQUIV="Pragma" CONTENT="no-cache"> 
  24.   <meta HTTP-EQUIV="Content-type" content="text/html; charset=UTF8"> 
  25.   </head> 
  26.   <body bgcolor="white"> 
  27.   <div align=center><font size=6><b>***my hosts monitor</b></font></div> 
  28.   <div align=center>check time: $Date_for_man</div> 
  29.   <p> 
  30.     <table width="60%" align=center border=3> 
  31.       <tr> 
  32.         <td nowrap>hostname</td> 
  33.         <td>IP</td> 
  34.         <td nowrap>min time</td> 
  35.         <td nowrap>max time</td> 
  36.         <td nowrap>avg time</td> 
  37.       </tr> 
  38. HEAD 
  39.  
  40. html_tr(){ 
  41.   if [ "$1" == "PingError" ] 
  42.   then 
  43.     cat<<TR >>$pahtml_now 
  44.     <tr> 
  45.         <td>host</td> 
  46.         <td>$ip</td> 
  47.         <td colspan=4><font color=red><b>can't reachable!!!</b></font></td> 
  48.     </tr> 
  49. TR 
  50.   else 
  51.     cat <<TR >>$pahtml_now 
  52.       <tr> 
  53.         <td>host</td> 
  54.         <td>$ip</td> 
  55.         <td>$rt_min ms</td> 
  56.         <td>$rt_max ms</td> 
  57.         <td>$rt_avg ms</td> 
  58.       </tr> 
  59. TR 
  60.  
  61.     fi 
  62. html_end(){ 
  63.   cat >>$pahtml_now<<END 
  64.     </table> 
  65.   </body> 
  66.   </html> 
  67. END 
  68.   ln -sf $pahtml_now $pahtml 
  69. #the main of the shell 
  70.  
  71. #check up the webpage head 
  72. html_head 
  73.  
  74. while read ip 
  75. do 
  76.   rt_min
  77.   rt_avg
  78.   rt_max
  79.   ping -c $pno $ip >tmp 
  80.   r=$(cat tmp|grep rtt) 
  81. if [ -n "$r" ] 
  82.   then 
  83.       rt_min=$(echo $r | awk '{print $4}'|awk -F/ '{print $1}') 
  84.       rt_avg=$(echo $r | awk '{print $4}'|awk -F/ '{print $2}') 
  85.       rt_max=$(echo $r | awk '{print $4}'|awk -F/ '{print $3}') 
  86.       html_tr $rt_min $rt_avg $rt_max 
  87.        
  88.    fi 
  89.   if [ -z $rt_min ] 
  90.   then 
  91.     html_tr PingError 
  92.   fi 
  93. done<$HostList 
  94. html_end 
  95. rm -f tmp 

 效果如图