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












没有评论:

发表评论

扩容/dev/mapper/pve-root

.执行 parted /dev/sdq 输入 print 找到要扩容的盘,应该是/dev/sdq3,检查大小 resizepart 3 100% quit 再检查大小 退出parted 更新物理卷的大小,当然这里前提是使用了LVM pvresize /dev/sda3 lvdis...