Ping 多个主机并执行命令

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

我不确定这是否正确。我在一个教程中使用过这个,但有些事情我不确定它们到底做了什么。

我在这里的路是对的还是完全错了?

答案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

答案2

甚至更加简洁

#!/bin/bash

服务器=(“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”)

对于“${servers[@]}”中的 i ;做
    ping -c 1 $i > /dev/null && /usr/bin/snmptrap -v 2c -c 公共 ...
完毕

注意: ping 后面的“&&”表示“IF TRUE THEN”,在 ping 的情况下,TRUE 表示 ping 没有失败(即服务器成功响应 ping)

相关内容