將在線/離線狀態寫入日誌文件

將在線/離線狀態寫入日誌文件

我正在尋找一種將 Linux 主機的線上/離線狀態記錄到本機日誌檔案的方法。

我嘗試使用ping此功能,但它沒有記錄超時/丟棄的包,它只顯示成功的傳輸: ping -D 8.8.8.8 | awk 'NR>1 { printf strftime("%c", $0) "%s",$2; }' RS=[ FS=]

Mi 14 Okt 2015 13:03:06 CEST 64 bytes from 8.8.8.8: icmp_req=155 ttl=55 time=18.4 ms
Mi 14 Okt 2015 13:03:07 CEST 64 bytes from 8.8.8.8: icmp_req=156 ttl=55 time=18.6 ms
Mi 14 Okt 2015 13:03:08 CEST 64 bytes from 8.8.8.8: icmp_req=157 ttl=55 time=18.4 ms
Mi 14 Okt 2015 13:05:19 CEST 64 bytes from 8.8.8.8: icmp_req=244 ttl=55 time=18.4 ms
Mi 14 Okt 2015 13:05:20 CEST 64 bytes from 8.8.8.8: icmp_req=245 ttl=55 time=18.4 ms

因此,我必須仔細查看請求編號以偵測離線狀態。

有誰知道更好的方法或可以為此命名一個工具嗎?

提前致謝。

答案1

已經有很多可用的工具可以做到這一點,例如 Munin、Nagios 等。

#!/bin/bash

logfile="/var/log/up-or-down.log";
ip_address_for_testing="192.168.1.10";

while [[ true ]]; do
    ping -c 5 $ip_address_for_testing;
    if [[ $? -eq 0 ]]; then
        echo "IP status for ${ip_address_for_testing}: UP" >> $logfile;
    else
        echo "IP status for ${ip_address_for_testing}: DOWN" >> $logfile;
    fi;
    sleep 5;
done;

上面的範例將向 $ip_address_for_testing 中定義的主機發送 5 個 ECHO REQUESTS,如果一切順利,它會在 $logfile 中寫入其狀態是正常還是正常。將其儲存到檔案中,使用chmod 賦予其執行權限,並透過/etc/rc.local 或/etc/rcS.d 呼叫它(如果您選擇第二個選項,則必須將其儲存在/etc/init中) .d 並建立一個符號連結)如果您想在啟動時啟動它。

呀!

相關內容