監控網站URL是否正常最常見的方法莫過於wget和curl命令了,這兩個命令都是非常強大,參數也非常多,下面列舉幾個常用的參數。
wget 常用命令參數:
--spider 模擬爬蟲的行為去訪問網站,但不會下載網頁
-q --quite 安靜的訪問,禁止輸出,類似-o /dev/null
-o --output-file=FILE 記錄到輸出文件
-T --timeout=SECONDS 訪問網站的超時時間
-t -tries=NUMBER 重試次數
curl 常用命令參數:
-I/--header 顯示響應頭信息
-m/--max-time<seconds> 訪問超時時間
-o/--output<file> 記錄訪問信息到文件
-s/--silent 靜默模式訪問,不輸出信息
-w/--write-output<format> 以固定格式輸出,例如%{http_code},輸出狀態碼
實際監控網站我們可以利用curl 或者wget 的返回值判斷網站是否正常:
[root@localhost ~]# wget --spider -T 5 -q -t 2 www.baidu.com [root@localhost ~]# echo $? 利用返回值確定網站是否正常 0
[root@localhost ~]# curl -s -o /dev/null www.baidu.com [root@localhost ~]# echo $? 0
獲取命令執行后的狀態碼:
[root@localhost ~]# curl -I -m 5 -s -w "%{http_code}\n" -o /dev/null www.baidu.com 200
監控url shell腳本:
#!/bin/bash usage() { echo $"useage:$0 url" exit 1 } check_url() { curl -s -o /dev/null $1 ## wget --spider -q -o /dev/null --tries=1 -T 5 $1 也可以使用wget獲取返回值 if [ $? -eq 0 ];then echo "$1 is ok" exit 0 else echo "$1 is fail" exit 1 fi } main() { if [ $# -ne 1 ];then usage fi check_url $1 } main $* #把所有命令行接收到的參數作為函數參數傳給函數內部