【问题标题】:How can I read in a service status and pass it on to Slack via JSON in bash如何读取服务状态并通过 bash 中的 JSON 将其传递给 Slack
【发布时间】:2014-10-15 12:02:02
【问题描述】:

我目前有这个脚本...

#!/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 配置测试的结果并将其推入。在运行此之前,nginx 重新加载开始,重新加载会自行进行配置检查,因此如果配置错误,服务器会保持运行状态。 所以我的 nginx 状态命令(有效)显示

NGINX
----------------
nginx (pid  1234) is running...

但我无法通过配置测试获得相同的结果,我预计这是由于所需转义的性质以及它抽出的其他垃圾 ala

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

【问题讨论】:

  • 考虑编辑您的问题以包含不起作用的“配置测试”命令行。这可能是一个引用问题。我会考虑将您要发送的任何输出重定向到文件中,然后使用curl 中的@/path/to/file_to_send 语法发送它,而不是尝试将结果嵌入到命令行中。
  • @shellter 我使用的是 nginxtest=$(service nginx configtest) 但配置测试返回多行消息并包含“它去锅
  • 你不能把那个输出传送到sed 并且只取你想要的行吗?即nginxstatCfg=$(service nginx configtest | sed -n '/stuff I want/p')? (同样,如果我们可以看到有问题的输出,我们可以给出更具体的答案 ;-))。祝你好运。

标签: json bash shell slack-api


【解决方案1】:

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

$ echo '"some quoted stuff"' | jq @json
"\"some quoted stuff\""

例如:

nginxstat=$(service nginx status | jq @json)

然后嵌入不带引号的。另请参阅manual

或者,如果您希望 JSON 转义,则 bash 转义:

echo '"some quoted stuff"' | jq "@json | @sh"
"'\"some quoted stuff\"'"

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

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

【讨论】:

  • 不错;以前没见过:)
  • 几个月前我才知道jq,我当时想“我这辈子都去哪儿了?”这就像 xpath 用于 JSON 等等。
猜你喜欢
  • 2012-04-12
  • 2019-03-06
  • 2019-03-26
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
相关资源
最近更新 更多