2017-07-10 49 views
0

我想用fping來ping包含在一個文件輸出失敗的IPS到一個文件中多個IP地址即fping的主機,並返回向下IPS

HOSTS.TXT

8.8.8.8 
8.8.4.4 
1.1.1.1 

ping.sh

#!/bin/bash 
HOSTS="/tmp/hosts.txt" 
fping -q -c 2 < $HOSTS 

if ip down 
echo ip > /tmp/down.log 
fi 

所以我想在down.log文件

回答

1

看來解析來自fping的數據有點困難。它允許爲活着但未死的主機分析數據。爲了解決這個問題,並且允許多個主機同時使用-f處理,所有活動的主機都放入一個名爲alive的變量中,然後/tmp/hosts.txt文件中的主機循環並grepped該變量用於解析主機是活着還是死亡。返回代碼1表示grep無法在活動中找到主機,因此除了down.log之外。

alive=$(fping -c 1 -f ipsfile | awk -F: '{ print $1 }') 
while read line 
do 
    grep -q -o $line <<<$alive 
    if [[ "$?" == "1" ]] 
    then 
      echo $line >> down.log 
    fi 
done < /tmp/hosts.txt 
+0

我需要使用fping -c(value)給出'1.1.1.1:xmt/rcv /%loss = 1/0/100%'的輸出,所以需要grep/awk'loss' – Lurch

+0

好的,我已經修改瞭解決方案 –

+0

謝謝嘗試新的和down.log是空白的? – Lurch

1

這裏用1.1.1.1落得是得到RESU的一種方式你想要的。但請注意;我沒有在腳本中的任何地方使用fping。如果fping的使用對你至關重要,那麼我可能完全錯過了這一點。

#!/bin/bash 

HOSTS="/tmp/hosts.txt" 

declare -i DELAY=$1 # Amount of time in seconds to wait for a packet 
declare -i REPEAT=$2 # Amount of times to retry pinging upon failure 

# Read HOSTS line by line 
while read -r line; do 
    c=0 
    while [[ $c < $REPEAT ]]; do 
     # If pinging an address does not return the word "0 received", we assume the ping has succeeded 
     if [[ -z $(ping -q -c $REPEAT -W $DELAY $line | grep "0 received") ]]; then 
      echo "Attempt[$((c + 1))] $line : Success" 
      break; 
     fi 

     echo "Attempt[$((c + 1))] $line : Failed" 

     ((c++)) 
    done 

    # If we failed the pinging of an address equal to the REPEAT count, we assume address is down 
    if [[ $c == $REPEAT ]]; then 
     echo "$line : Failed" >> /tmp/down.log # Log the failed address 
    fi 

done < $HOSTS 

用法:./script [延遲] [repeatCount] - 「延遲」是我們等待來自平的響應的秒的總量,「repeatCount」被重試我們多少次失敗時執行ping在決定地址關閉之前。

在這裏,我們正在逐行閱讀/tmp/hosts.txt並使用ping評估每個地址。如果ping地址成功,我們繼續下一個。如果地址失敗,我們會再次嘗試用戶指定的次數。如果地址不能ping通所有ping,我們將其登錄到我們的/tmp/down.log

檢查ping失敗/成功的條件可能對您的用例不準確,因此您可能需要編輯它。儘管如此,我希望這會得到一個普遍的想法。

+0

這就是那個,但我特別需要fping。 – Lurch