ネットワークに接続できない場合(繰り返し)pingを開始する方法はありますか?

ネットワークに接続できない場合(繰り返し)pingを開始する方法はありますか?

ネットワークがダウンしても、私のpingコマンド(Debian 6または7)は繰り返しサーバーにpingを試みます。もし起動時にネットワークが稼働しています。ネットワークがダウンしたときにpingを開始し、同じ動作を得る方法はありますか?

ここに例があります。ネットワークが稼働しているときに繰り返し ping を開始し、ping の実行中にネットワークがダウンしても、ping は繰り返されます。ネットワークが再び動作している場合は、pingを送信し続けます。

me@here:~$ ping -n 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_req=1 ttl=46 time=117 ms
...
64 bytes from 8.8.8.8: icmp_req=6 ttl=46 time=116 ms
ping: sendmsg: Network is unreachable
...
ping: sendmsg: Network is unreachable
64 bytes from 8.8.8.8: icmp_req=108 ttl=46 time=694 ms
...

ただし、pingを実行したときにネットワークがダウンしている場合:

me@here:~$ ping -n 8.8.8.8
connect: Network is unreachable
me@here:~$

接続できないネットワークの問題と同じですが、以前のようにネットワークが再び表示されるまでpingは試行されません。

ベストアンサー1

シェルスクリプトでwhileループを使用できます。

failed=1 # any number not equal to zero
while [ $failed -ne 0 ]
do
   ping -n 8.8.8.8
   failed=$?
done
# after the  $? becomes "0" it will get out of the while loop
echo "ping succeeded"

connect: Network is unreachableメッセージの印刷を停止するには、pingを使用して次のように行を編集できます。

ping -n 8.8.8.8 2> /dev/null

あるいは、sleepループに 1 つを追加して、これらのメッセージの数を減らすこともできます。

スクリプトは次のように単純化できます。

while ! ping -n 8.8.8.8
do
    sleep 1
done

これにより、1行で書くことができます。

while ! ping -n 8.8.8.8; do sleep 1; done

おすすめ記事