ネットワーク接続がないときに再起動すると動作しません!

ネットワーク接続がないときに再起動すると動作しません!

ローカルネットワークのNASとして使用するRaspberry Piがあります。うまく動作しますが、パイが接続されているルーターの電源を切ると、接続が永久に切断されます。ネットワークに再接続するには再起動する必要があります。だから私は次のスクリプトを書いた。

#!/bin/bash

if ! ping -q -w 1 -c 1 $(ip r | grep default | cut -d ' ' -f 3)
then
        service networking restart

        sleep 60

        if ! ping -q -w 1 -c 1 $(ip r | grep default | cut -d ' ' -f 3)
        then
                reboot
        fi
fi

デフォルトではルータにpingを試みます。失敗した場合は、ネットワークサービスを再起動します(単純なエラーが発生して再起動する必要がない場合)。それでもルーターをpingできない場合は再起動します。 10分ごとにcronjobを実行するように設定しましたが、機能しません。私は何が間違っていましたか?

私はcrontabに次の行を入れました。

0,10,20,30,40,50 * * * * /root/rebooter.sh >> rebooter.log 2>&1

接続がありません。出力は次のとおりです。

Usage: ping [-LRUbdfnqrvVaAD] [-c count] [-i interval] [-w deadline]
            [-p pattern] [-s packetsize] [-t ttl] [-I interface]
            [-M pmtudisc-hint] [-m mark] [-S sndbuf]
            [-T tstamp-options] [-Q tos] [hop1 ...] destination
/root/rebooter.sh: Line 5: service: Command not found.
Usage: ping [-LRUbdfnqrvVaAD] [-c count] [-i interval] [-w deadline]
            [-p pattern] [-s packetsize] [-t ttl] [-I interface]
            [-M pmtudisc-hint] [-m mark] [-S sndbuf]
            [-T tstamp-options] [-Q tos] [hop1 ...] destination
/root/rebooter.sh: Line 11: reboot: Command not found.

接続後の出力は次のようになります。

PING 192.168.178.1 (192.168.178.1) 56(84) bytes of data.

--- 192.168.178.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.985/0.985/0.985/0.000 ms

ベストアンサー1

問題はあなたのif公式にあると思います。

if ! ping -q -w 1 -c 1 $(ip r | grep default | cut -d ' ' -f 3)

だけでなく:

ping -q -w 1 -c 1 $(ip r | grep default | cut -d ' ' -f 3)

ホストがip正しく配信されませんでした。

各部分は独立して動作します(例:ping hostsum ip r....)。

これはいつも私にとって効果的でした。

$ ip r | grep "default" | cut -d ' ' -3 | xargs ping -q -w 1 -c 1

これをあなたの声明にリンクしてくださいifxargs古いパイプの出力を取得し、pingIPがpingコードの半分に渡されずに使用されます。コマンドラインで試してみてください :-)

netstatむしろ変更するとip rPiでも機能しますが、他のLinuxディストリビューションでも利用できるほど一般的です。

以下のスクリプト:

0pingするホスト名を正しく取得し、入力(入力、つまりデバイスが切断された場合)が発生した場合は、ステートメントを入力します。

ifまた、括弧を使用してステートメントを再構成し、[]より明確なステートメントに変数を割り当てました。

#!/bin/bash

test_host=`netstat -nr | grep "UG" | awk '{ print $2}' | xargs ping -q -w 1 -c 1 | grep "received" | awk '{ print $4 }'`
if [ "$test_host" == "0" ] || [ -z "$test_host" ] ;
then
    echo "service networking restart"

    sleep 60
    test_host=`netstat -nr | grep "UG" | awk '{ print $2}' | xargs ping -q -w 1 -c 1 | grep "received" | awk '{ print $4 }'`
    if [ "$test_host" == "0" ] || [ -z "$test_host" ] ;
    then
            echo "reboot"
    fi
fi

おすすめ記事