如何评估来自 bash/shell 脚本的 http 响应代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2220301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to evaluate http response codes from bash/shell script?
提问by Olaf Kock
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.
我有一种感觉,我错过了明显的,但没有成功man [curl|wget]
或谷歌(“http”使搜索词如此糟糕)。我正在寻找对我们的一个经常失败的网络服务器的快速和肮脏的修复,返回状态代码 500 并显示错误消息。一旦发生这种情况,它需要重新启动。
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.
建议的解决方案是创建一个每 5 分钟运行一次的 cron 作业,检查http://localhost:8080/。如果返回状态码 500,则网络服务器将重新启动。服务器将在一分钟内重新启动,因此无需检查已启动的重新启动。
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.
有问题的服务器是 ubuntu 8.04 最小安装,只安装了足够的软件包来运行它当前需要的东西。在 bash 中执行任务没有硬性要求,但我希望它在这样一个最小的环境中运行,而无需安装更多的解释器。
(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.)
(我对脚本非常熟悉,将 http 状态代码分配给环境变量的命令/选项就足够了 - 这是我一直在寻找但找不到的东西。)
回答by Paused until further notice.
I haven't tested this on a 500 code, but it works on others like 200, 302 and 404.
我没有在 500 代码上测试过这个,但它适用于 200、302 和 404 等其他代码。
response=$(curl --write-out %{http_code} --silent --output /dev/null servername)
As suggested by @ibai, add --head
to make a HEAD only request. This will save time when the retrieval is successful since the page contents won't be transmitted.
按照@ibai 的建议,添加--head
以仅发出 HEAD 请求。这将在检索成功时节省时间,因为不会传输页面内容。
回答by hd1
curl --write-out "%{http_code}\n" --silent --output /dev/null "$URL"
works. If not, you have to hit return to view the code itself.
作品。如果没有,您必须按回车键查看代码本身。
回答by Chris Gillatt
I needed to demo something quickly today and came up with this. Thought I would place it here if someone needed something similar to the OP's request.
我今天需要快速演示一些东西并想出了这个。如果有人需要类似于 OP 的请求,我想我会把它放在这里。
#!/bin/bash
status_code=$(curl --write-out %{http_code} --silent --output /dev/null www.bbc.co.uk/news)
if [[ "$status_code" -ne 200 ]] ; then
echo "Site status changed to $status_code" | mail -s "SITE STATUS CHECKER" "[email protected]" -r "STATUS_CHECKER"
else
exit 0
fi
This will send an email alert on every state change from 200, so it's dumb and potentially greedy. To improve this, I would look at looping through several status codes and performing different actions dependant on the result.
这将在从 200 开始的每个状态更改时发送电子邮件警报,因此它很愚蠢且可能贪婪。为了改进这一点,我会考虑遍历几个状态代码并根据结果执行不同的操作。
回答by nicerobot
Although the accepted responseis a good answer, it overlooks failure scenarios. curl
will return 000
if there is an error in the request or there is a connection failure.
尽管接受的响应是一个很好的答案,但它忽略了失败场景。如果请求中有错误或连接失败,curl
将返回000
。
url='http://localhost:8080/'
status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == 500 ]] || [[ $status == 000 ]] && echo restarting ${url} # do start/restart logic
Note: this goes a little beyond the requested 500
status check to also confirm that curl
can even connect to the server (i.e. returns 000
).
注意:这稍微超出了请求的500
状态检查,以确认curl
甚至可以连接到服务器(即返回000
)。
Create a function from it:
从中创建一个函数:
failureCode() {
local url=${1:-http://localhost:8080}
local code=${2:-500}
local status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == ${code} ]] || [[ $status == 000 ]]
}
Test getting a 500
:
测试得到一个500
:
failureCode http://httpbin.org/status/500 && echo need to restart
Test getting error/connection failure (i.e. 000
):
测试获取错误/连接失败(即000
):
failureCode http://localhost:77777 && echo need to start
Test not getting a 500
:
测试没有得到500
:
failureCode http://httpbin.org/status/400 || echo not a failure
回答by marco
With netcat and awk you can handle the server response manually:
使用 netcat 和 awk,您可以手动处理服务器响应:
if netcat 127.0.0.1 8080 <<EOF | awk 'NR==1{if ( == "500") exit 0; exit 1;}'; then
GET / HTTP/1.1
Host: www.example.com
EOF
apache2ctl restart;
fi
回答by siliconrockstar
To follow 3XX redirects and print response codes for all requests:
要遵循 3XX 重定向并为所有请求打印响应代码:
HTTP_STATUS="$(curl -IL --silent example.com | grep HTTP )";
echo "${HTTP_STATUS}";
回答by dkinzer
Another variation:
另一种变体:
status=$(curl -sS -I https://www.healthdata.gov/user/login 2> /dev/null | head -n 1 | cut -d' ' -f2)
status_w_desc=$(curl -sS -I https://www.healthdata.gov/user/login 2> /dev/null | head -n 1 | cut -d' ' -f2-)
回答by Thomas Praxl
Here comes the long-winded – yet easy to understand – script, inspired by the solution of nicerobot, that only requests the response headers and avoids using IFS as suggested here. It outputs a bounce message when it encounters a response >= 400. This echo can be replaced with a bounce-script.
这是冗长但易于理解的脚本,其灵感来自于nicerobot的解决方案,它只请求响应标头并避免使用此处建议的 IFS 。它在遇到响应 >= 400 时输出一个弹跳消息。这个回声可以用一个弹跳脚本代替。
# set the url to probe
url='http://localhost:8080'
# use curl to request headers (return sensitive default on timeout: "timeout 500"). Parse the result into an array (avoid settings IFS, instead use read)
read -ra result <<< $(curl -Is --connect-timeout 5 "${url}" || echo "timeout 500")
# status code is second element of array "result"
status=${result[1]}
# if status code is greater than or equal to 400, then output a bounce message (replace this with any bounce script you like)
[ $status -ge 400 ] && echo "bounce at $url with status $status"
回答by Tango
this can help to evaluate http status
这可以帮助评估 http 状态
var=`curl -I http://www.example.org 2>/dev/null | head -n 1 | awk -F" " '{print }'`
echo http:$var
回答by nathan g
i didn't like the answers here that mix the data with the status. found this: you add the -f flag to get curl to fail and pick up the error status code from the standard status var: $?
我不喜欢这里将数据与状态混合在一起的答案。发现这一点:您添加 -f 标志以使 curl 失败并从标准状态变量中获取错误状态代码:$?
https://unix.stackexchange.com/questions/204762/return-code-for-curl-used-in-a-command-substitution
https://unix.stackexchange.com/questions/204762/return-code-for-curl-used-in-a-command-substitution
i don't know if it's perfect for every scenario here, but it seems to fit my needs and i think it's much easier to work with
我不知道它是否适合这里的每个场景,但它似乎符合我的需求,而且我认为它更容易使用