天天看點

Linux Shell腳本實作批量PING測試Linux Shell腳本實作批量PING測試

Linux Shell腳本實作批量PING測試

需求:

通過Linux伺服器定時ping驗證目标IP位址連通情況。

目标IP位址以TXT檔案方式存儲在本地。

生成的測試記錄包含測試時間、目标IP位址、連通情況。

1、測試目的IP位址清單

39.156.66.18
203.119.129.109
111.30.164.236           
Linux Shell腳本實作批量PING測試Linux Shell腳本實作批量PING測試

2、批量PING腳本

#!/bin/bash
#
#擷取目前時間
datetimevar=`date "+%Y-%m-%d %H:%M:%S"`
#讀取IP清單行數
lineNumber=`cat iplist.txt |wc -l`
#設定計數參數
count=0
#循環讀取IP并測試
for i in `cat ./iplist.txt`
    do
        #計數器
        count=$((count+1))
        #控制台列印目前進度
        echo "${i} ${count}/${lineNumber}"
        #PING并保留丢包數
        p=`ping -c 1 $i|grep loss|awk '{print $6}'|awk -F "%" '{print $1}'`
            #因為隻PING一次,丢包數為0則表示成功,否則失敗
            if [ $p -eq 0 ]
                then
                    echo "${datetimevar}|${i}|true" >> ./ipcheckdown.txt
                else
                    echo "${datetimevar}|${i}|fail" >> ./ipcheckdown.txt
            fi
    done           
Linux Shell腳本實作批量PING測試Linux Shell腳本實作批量PING測試

3、設定腳本檔案運作權限

chmod +x pingtest.sh

Linux Shell腳本實作批量PING測試Linux Shell腳本實作批量PING測試

4、執行腳本(回顯執行進度)

./pingtest.sh

Linux Shell腳本實作批量PING測試Linux Shell腳本實作批量PING測試

5、檢視結果

cat ipcheckdown.txt

Linux Shell腳本實作批量PING測試Linux Shell腳本實作批量PING測試

6、添加定時任務,設定每分鐘運作一次

crontab -e

*/1 * * * * /root/pingtest.sh

Linux Shell腳本實作批量PING測試Linux Shell腳本實作批量PING測試

7、運作情況(是否顯示與具體系統設定有關)

自動執行後系統提示“您在 /var/spool/mail/root 中有新郵件”

Linux Shell腳本實作批量PING測試Linux Shell腳本實作批量PING測試

檢視結果

Linux Shell腳本實作批量PING測試Linux Shell腳本實作批量PING測試

8、備注

通過Windows系統編輯的檔案在Linux中執行時,若由于檔案格式問題導緻報錯,例如:

(1)腳本字元格式異常:

【/bin/bash^M: 壞的解釋器: 沒有那個檔案或目錄】

(2)IP清單格式問題導緻腳本讀取IP異常:

【:未知的名稱或服務- 5 ./pingtest.sh第17行•••】

(3)問題原因:

在Windows下每一行結尾是nr,而Linux下則是n,是以才會有多出來的r。

修改方式:

使用指令

sed -i 's/\r$//' 檔案名

,将上面的指令會把檔案中的r 替換成空白。

Yunxi.D

2020-06-04

2020-06-10(追加)

繼續閱讀