How to evaluate http response codes from bash/shell script?

I have the feeling that I'm missing the obvious, but have not succeeded with man [curl|wget] or google ("http" makes such a bad search term). I'm looking for a quick&dirty fix to one of our webservers that frequently fails, returning status code 500 with an error message. Once this happens, it needs to be restarted.

As the root cause seems to be hard to find, we're aiming for a quick fix, hoping that it will be enough to bridge the time until we can really fix it (the service doesn't need high availability)

The proposed solution is to create a cron job that runs every 5 minutes, checking http://localhost:8080/. If this returns with status code 500, the webserver will be restarted. The server will restart in under a minute, so there's no need to check for restarts already running.

The server in question is a ubuntu 8.04 minimal installation with just enough packages installed to run what it currently needs. There is no hard requirement to do the task in bash, but I'd like it to run in such a minimal environment without installing any more interpreters.

(I'm sufficiently familiar with scripting that the command/options to assign the http status code to an environment variable would be enough - this is what I've looked for and could not find.)


我没有在500代码上测试过这个,但它在200,302和404等其他代码上工作。

response=$(curl --write-out %{http_code} --silent --output /dev/null servername)

curl --write-out "%{http_code}n" --silent --output /dev/null "$URL"

works. If not, you have to hit return to view the code itself.


Here:

url='http://localhost:8080/'
status=$(r=(IFS=' ';$(curl -Is --connect-timeout 5 "${url}" || echo 1 500));echo ${r[1]})
[ status -eq 500 ] && bounce # assuming the bounce script is called 'bounce'

Or put it all on one line:

[ 500 -eq $(r=(IFS=' ';$(curl -Is --connect-timeout 5 'http://localhost:8080/' || echo 1 500));echo ${r[1]}) ] && bounce

To explain, the HTTP response always contains the server status as part of the first line of the response, like:

HTTP/1.1 200 OK
HTTP/1.0 404 NOT FOUND

The script just uses curl to do a HEAD request to localhost:8080. It converts the HTTP header to an array and returns the second element. To simplify some failure handling, if the HEAD fails to connect within 5 seconds or curl fails for some reason, 500 is also returned.

链接地址: http://www.djcxy.com/p/45606.html

上一篇: 在脚本中发送多个HTTP状态码

下一篇: 如何评估来自bash / shell脚本的http响应代码?