通过脚本判断远程Web服务器状态码是否正常


  1. 说明:

    (1)生产环境常见的HTTP状态码列表,请查看我的博文:http://wutengfei.blog.51cto.com/10942117/1934645

    (2)实验中远程nginx服务器IP地址:192.168.100.114

       本地客户端IP地址:192.168.100.118

  2. 脚本如下

方法1:if

#!/bin/bash

httpcode=`curl -I -s 192.168.100.114|head -1|cut -d " " -f2`

if [ "$httpcode" == "200" ];then

        echo "nginx is running."

else

        echo "nginx is not running."

fi

验证结果如下:

开启nginx服务

wKiom1lmMUOB2nAXAAANTG3xlxk248.png

在客户端执行脚本:

wKiom1lmMYqRx47cAAAJRXT2nq0061.png

现在关闭nginx服务:

wKiom1lmMfaDpi6bAAAWBZvSb34855.png

在客户端执行脚本:

wKioL1lmMlewhffLAAAJ74AnXAQ995.png

方法2:利用传参

#!/bin/bash

if [ $# -ne 1 ];then

        echo "Usage:$0 IP port."

fi

httpcode=`curl -I -s $1|head -1|cut -d " " -f2`

if [ "$httpcode" == "200" ];then

        echo "nginx is running."

else

        echo "nginx is not running."

fi

验证结果如下:

开启nginx服务

wKiom1lmMUOB2nAXAAANTG3xlxk248.png

在客户端执行脚本:

wKioL1lmOMSg6Iz6AAALjClRT6g702.png

现在关闭nginx服务:

wKiom1lmMfaDpi6bAAAWBZvSb34855.png

在客户端执行脚本:

wKiom1lmOSTxnkybAAANdoZY5QM869.png

方法3:利用read,界面比较友好

#!/bin/bash

read -p "please input IP:" a

if [ -z $a ];then

        echo "Usage:$0 please input ip."

fi

httpcode=`curl -I -s $a|head -1|cut -d " " -f2`

if [ "$httpcode" == "200" ];then

        echo "nginx is running."

else

        echo "nginx is not running."

fi

验证结果如下:

开启nginx服务

wKiom1lmMUOB2nAXAAANTG3xlxk248.png

在客户端执行脚本:

wKiom1lmOuqiWCfdAAAOh5PnW2k901.png

现在关闭nginx服务:

wKiom1lmMfaDpi6bAAAWBZvSb34855.png

在客户端执行脚本:

wKioL1lmO0WxJrA-AAAPqRodhRM887.png

方法4:利用函数

#!/bin/bash

[ -f /etc/init.d/functions ] && . /etc/init.d/functions || exit 1

read -p "please input IP:" a

httpcode=`curl -I -s $a |head -1|cut -d " " -f2`

if [ "$httpcode" == "200" ];then

        action "nginx is running." /bin/true

else

        action "nginx is not running." /bin/false

fi

验证结果如下:

开启nginx服务

wKiom1lmMUOB2nAXAAANTG3xlxk248.png

在客户端执行脚本:

wKioL1lmPoKBLO6rAAAQeUGlLVk564.png

现在关闭nginx服务:

wKiom1lmMfaDpi6bAAAWBZvSb34855.png

在客户端执行脚本:

wKiom1lmPuqyiQgeAAAQodDkXI8010.png