複数のホストをpingしてコマンドを実行します。

複数のホストをpingしてコマンドを実行します。

私はbashスクリプトとUnixに初めて触れたので、助けが必要です。 7〜10個のホストがあり、cronjobを介してサーバーの1つでホストをpingしたいと思います。私が望むのは、ホストがコマンドを実行できるときです。落とすと何も起こりません。

ログやメッセージは必要ありません。私はこれを持っていますが、残念ながらまだそれを試す能力はありません。確認してご指摘いただきありがとうございます。

#!/bin/bash
servers=( "1.1.1.1" "2.2.2.2" "3.3.3.3" "4.4.4.4" "5.5.5.5" "6.6.6.6" "7.7.7.7" )

for i in "${servers[@]}"
do
  ping -c 1 $i > /dev/null  
done

ping -c 1 $i > /dev/null
if [ $? -ne 0 ]; then

    if [ $STATUS >= 2 ]; then
        echo ""
    fi
else
    while [ $STATUS <= 1 ];
    do 
       # command should be here where is status 1 ( i.e. Alive )
       /usr/bin/snmptrap -v 2c -c public ...
    done
fi

これが正しいかどうかはわかりません。チュートリアルでこれを使用しましたが、正確に何をするのかわからない部分があります。

私はここで正しい道を進んでいますか、それとも完全に間違っていますか?

ベストアンサー1

スクリプトの他の部分が何をしているかを説明するために、いくつかの説明を書きました。その後、以下のスクリプトの簡潔なバージョンを作成しました。

#!/bin/bash
servers=( "1.1.1.1" "2.2.2.2" "3.3.3.3" "4.4.4.4" "5.5.5.5" "6.6.6.6" "7.7.7.7" )

# As is, this bit doesn't do anything.  It just pings each server one time 
# but doesn't save the output

for i in "${servers[@]}"
do
  ping -c 1 $i > /dev/null  
# done
# "done" marks the end of the for-loop.  You don't want it to end yet so I
# comment it out

# You've already done this above so I'm commenting it out
#ping -c 1 $i > /dev/null

    # $? is the exit status of the previous job (in this case, ping).  0 means
    # the ping was successful, 1 means not successful.
    # so this statement reads "If the exit status ($?) does not equal (-ne) zero
    if [ $? -ne 0 ]; then
        # I can't make sense of why this is here or what $STATUS is from
        # You say when the host is down you want it to do nothing so let's do
        # nothing
        #if [ $STATUS >= 2 ]; then
        #    echo ""
        #fi
        true
    else
        # I still don't know what $STATUS is
        #while [ $STATUS <= 1 ];
        #do 
           # command should be here where is status 1 ( i.e. Alive )
           /usr/bin/snmptrap -v 2c -c public ...
        #done
    fi

# Now we end the for-loop from the top
done

各サーバーにパラメータが必要な場合は、forループにパラメータ配列とインデックス変数を作成します。インデックスを介してパラメータにアクセスする:

#!/bin/bash
servers=( "1.1.1.1" "2.2.2.2" "3.3.3.3" "4.4.4.4" "5.5.5.5" "6.6.6.6" "7.7.7.7" )
params=(PARAM1 PARAM2 PARAM3 PARAM4 PARAM5 PARAM6 PARAM7)

n=0
for i in "${servers[@]}"; do
    ping -c 1 $i > /dev/null  

    if [ $? -eq 0 ]; then
       /usr/bin/snmptrap -v 2c -c public ${params[$n]} ...
    fi

    let $((n+=1)) # increment n by one

done

おすすめ記事