Shell
ping 多台主機並執行命令
我是 bash 腳本和 unix 方面的新手,所以我需要一些幫助。我有 7-10 台主機,我想通過 cronjobs 從其中一台伺服器 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
我不確定這是否正確。我在一個教程中使用過這個,有些事情我不確定它們到底做了什麼。
我在這裡是正確的方式還是我完全錯了?
我已經做了一些評論來解釋腳本的不同部分在做什麼。然後,我製作了以下腳本的簡明版本。
#!/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