如何评估来自 bash/shell 脚本的 http 响应代码? [英] How to evaluate http response codes from bash/shell script?

查看:21
本文介绍了如何评估来自 bash/shell 脚本的 http 响应代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感觉我错过了明显的东西,但没有成功使用 man [curl|wget] 或 google(http" 是一个糟糕的搜索词).我正在为我们的一个经常失败的网络服务器寻找一个快速而肮脏的修复程序,返回状态代码 500 和错误消息.一旦发生这种情况,就需要重新启动.

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)

建议的解决方案是创建一个每 5 分钟运行一次的 cron 作业,检查 http://localhost:8080/.如果返回状态码 500,则网络服务器将重新启动.服务器将在一分钟内重新启动,因此无需检查是否已重新启动.

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.

有问题的服务器是 ubuntu 8.04 最小安装,安装了足够的软件包来运行它当前需要的.在 bash 中完成任务没有硬性要求,但我希望它在这样一个最小的环境中运行,而无需安装任何更多的解释器.

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.

(我对脚本非常熟悉,将 http 状态代码分配给环境变量的命令/选项就足够了 - 这是我一直在寻找但找不到的.)

(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 等其他代码.

I haven't tested this on a 500 code, but it works on others like 200, 302 and 404.

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

注意,为 --write-out 提供的格式应该被引用.正如@ibai 所建议的,添加 --head 以发出仅 HEAD 请求.由于页面内容不会被传输,这将在检索成功时节省时间.

Note, format provided for --write-out should be quoted. 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.

这篇关于如何评估来自 bash/shell 脚本的 http 响应代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆