Shell脚本实现批量Ping功能(弱鸡版和弱鸡增强版)

Ping--弱鸡版

适合需要大量ping不同主机的用户


#脚本正文,建议chmod +x p.sh后,使用 ./p.sh执行即可

cat p.sh 
#! /bin/bash
#把需要测试的Host填进下列双引号内,每行一条记录
echo "
www.itpwd.com
www.aliyun.com
" > /tmp/tmp_IPList.txt

for i in `cat /tmp/tmp_IPList.txt`
do
ping=`ping -c 1 $i|grep loss|awk '{print $6}'|awk -F "%" '{print $1}'`
if [ $ping -eq 100  ];then
echo ping $i fail
else
echo ping $i ok
fi
done


------------------------我是娇气的分割线------------------------


Ping--弱鸡增强版

监控的每个Host记录按照月份保存记录


#文件路径

pwd
/root/shell  #以下文件均放入此路径


#脚本正文,增加执行权限 chmod +x ping.sh

cat ping.sh 
#! /bin/bash

for i in `cat /root/shell/IPList.txt`
do
ping=`ping -c 1 $i|grep loss|awk '{print $6}'|awk -F "%" '{print $1}'`
datestr=`date '+%Y-%m-%d %H:%M:%S'`
datem=`date '+%Y%m'`

if [ ! -d "/root/shell/log/$datem" ]; then
  mkdir -p /root/shell/log/$datem
fi

file="/root/shell/log/"$datem"/"$datem"_"$i".csv"
if [ ! -f "$file" ]; then
  touch "$file"
  echo Time,Type,Host,Status >> $file
fi

#t=`grep -c "" $file`
#if [ $t -ge 100 ];then  #如果大于100行记录
#sed -i '1,10d' $file  #删除开始的1-10行记录
#fi

if [ $ping -eq 100  ];then
echo $datestr,ping,$i,fail >> $file
else
echo $datestr,ping,$i,ok >> $file
fi
done


#需要Ping的网址&IP地址,每行一条记录

cat IPList.txt 
www.itpwd.com
www.aliyun.com


加入crontab每分钟执行

crontab -l
*/1 * * * * source ~/.bash_profile;/bin/sh /root/shell/ping.sh


#查看最近5分钟记录,每分钟自动刷新

 watch -n 60 'cd log/`date '+%Y%m'`/ && tail -n 5 *'



评论

  • *
  • *