2022年9月17日星期六

使用ping检测主机是否连通,并执行特定命令

 

ping -c 1 127.0.0.1 &> /dev/null && echo success || echo fail

ping -c 1 127.0.0.1 ; echo $?
# 0

ping -c 1 192.168.1.5 ; echo $?
# 2

0 means host reachable

1  Destination Host Unreachable

2 means unreachable





if ping -c 1 some_ip_here &> /dev/null
then
  echo 1
else
  echo 0
fi

There is advanced version of ping - "fping", which gives possibility to define the timeout in milliseconds.

#!/bin/bash
IP='192.168.1.1'
sudo ping -c1 -t 200 $IP 2>/dev/null 1>/dev/null
if [ "$?" = 0 ]
then
  echo "Host found"
else
  echo "Host not found"
fi


This is a complete bash script which pings target every 5 seconds and logs errors to a file.

Enjoy!

#!/bin/bash
        
        FILE=errors.txt
        TARGET=192.168.0.1

          touch $FILE
          while true;
          do
            DATE=$(date '+%d/%m/%Y %H:%M:%S')
            ping -c 1 $TARGET &> /dev/null
            if [[ $? -ne 0 ]]; then
              echo "ERROR "$DATE
              echo $DATE >> $FILE
            else
              echo "OK "$DATE
            fi
              sleep 5
          done


for i in `cat Hostlist`
do  
  ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done












没有评论:

发表评论

youtube的dns屏蔽方法

  216.239.38.120 是 Google 提供的一个特殊 DNS 服务器,用于强制开启 YouTube 受限模式(Restricted Mode) 。 如果你想在家里强制 YouTube 进入受限模式,可以在 路由器的 DNS 设置 中配置以下 DNS 服务器: D...