简单shell脚本结合curl检查nginx服务器状态

829 查看

本地搭建了虚拟主机,git.com

说一下shell中curl几个常用参数,curl实在太强大。可通过man curl查看详细信息。

-m 最大传输时间
-s slient输出
-w 格式化输出
-o 保留到文件,-O可以保留文件名字
-i i是输入http头部和内容
-I -I是只是输出HTTP头部

其他curl参数详解

    curl -m 5 -s -w %{http_code}-o /home/index.html git.com
    
    HTTP/1.1 200 OK
    Server: nginx/1.4.6 (Ubuntu)
    Date: Tue, 05 Jan 2016 03:22:12 GMT
    Content-Type: text/html
    Content-Length: 24
    Last-Modified: Wed, 30 Dec 2015 06:05:47 GMT
    Connection: keep-alive
    ETag: "5683743b-18"
    Accept-Ranges: bytes


200

root@tb:/home/tb250# curl -m 5 -s -w %{http_code} -i git.com

HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Tue, 05 Jan 2016 03:23:00 GMT
Content-Type: text/html
Content-Length: 24
Last-Modified: Wed, 30 Dec 2015 06:05:47 GMT
Connection: keep-alive
ETag: "5683743b-18"
Accept-Ranges: bytes

hello git

hello git 10

200

vim check_nginx_server.sh

#!/bin/bash
NginxServer='git.com'
Check_Nginx_Server()
{

    http_status_code=$(curl -m 5 -s -i  -w %{http_code} -o/home/index.html $NginxServer)
    if [ $http_status_code -eq 000 -o $http_status_code -ge 500 ];then
            echo "check http server error \nhttp_status_code is"  $http_status_code
    else
            http_content=$(curl -s ${NginxServer}) 
            echo "service status ok\n"$http_content
           
    fi

}

Check_Nginx_Server

测试nginx开启和停用状态对此脚本影响

root@tb:/home/tb250# sh  check_server.sh 
service status ok
hello git hello git 10
root@tb:/home/tb250# service nginx stop
root@tb:/home/tb250# sh  check_server.sh 
check http server error 
http_status_code is 000
root@tb:/home/tb250# service nginx start
root@tb:/home/tb250# sh  check_server.sh 
service status ok
hello git hello git 10