首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何读取服务状态并通过bash中的JSON将其传递给Slack

如何读取服务状态并通过bash中的JSON将其传递给Slack
EN

Stack Overflow用户
提问于 2014-10-15 12:02:02
回答 1查看 1.2K关注 0票数 2

我现在有这个剧本..。

代码语言:javascript
运行
复制
#!/bin/bash
# Check NGINX
nginxstat=$(service nginx status)

# Checking Sites
hostsite="localhost:81 - "$(curl --silent --head --location --output /dev/null --write-out '%{http_code}'  http://localhost:81 | grep '^2')

##########
# Send to Slack
curl -X POST --data '{"channel":"#achannel","username":"Ansible", "attachments": [{"fallback":"NGINX Reload","pretext":"'"$HOSTNAME"'","color":"good","fields":[{"title":"nginx localhost","value":"'"$hostsite"'","short":true},{"title":"NGINX","value":"'"$nginxstat"'","short":true}]}]}' -i https://xxx.slack.com/services/hooks/incoming-webhook?token=xxx

我尝试并尝试失败;我想获取nginx configtest的结果并将其插入。在运行之前,nginx重新加载就会启动,重新加载本身就会进行configcheck,因此如果配置错误,服务器就会继续运行。因此,我的nginx状态命令(它可以工作)显示

代码语言:javascript
运行
复制
NGINX
----------------
nginx (pid  1234) is running...

但是我不能用配置测试做同样的工作,我希望这是由于所需的逃逸的性质以及它从ala中排出的其他垃圾。

代码语言:javascript
运行
复制
nginx: [warn] "ssl_stapling" ignored, issuer certificate not found
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-15 16:27:04

在将变量嵌入POST数据之前,将变量转换为带有jq的JSON字符串:

代码语言:javascript
运行
复制
$ echo '"some quoted stuff"' | jq @json
"\"some quoted stuff\""

例如:

代码语言:javascript
运行
复制
nginxstat=$(service nginx status | jq @json)

然后嵌入未引用的内容。也见手册

或者,如果您想要它,JSON逃脱了,那么bash逃脱了:

代码语言:javascript
运行
复制
echo '"some quoted stuff"' | jq "@json | @sh"
"'\"some quoted stuff\"'"

我有没有提过jq是我最喜欢的东西?

http://stedolan.github.io/jq/

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26382087

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档