在Bash脚本中传递参数的CURL API

2024-05-28 11:16:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在ICINGA API中传递参数的Curl命令:

我有一个curl命令并将其传递到Bash脚本中,我需要在POST方法中为这个URL设置两个变量,如何将参数传递给curl命令

curl -k -s -u 'root:icinga' -H 'Accept: application/json' \
  -X POST 'https://sample.com:5665/v1/actions/acknowledge-problem?type=Service' \
  -d '{ "author": "icingaadmin", "comment": " Working on it.", "notify": true, "filter": "host.name == {\"$1\} && service.name == {\"$2\}"" }''' \
  | python -m json.tool

$1和$2应该分别具有主机名和服务名

请帮忙

谢谢 阿拉文德


Tags: 方法name命令脚本bashapijsonurl
1条回答
网友
1楼 · 发布于 2024-05-28 11:16:56

如果在bash中使用单引号('like this'),则会得到一个没有变量扩展的文本字符串。也就是说,比较:

$ echo '$DISPLAY'
$DISPLAY

有:

^{pr2}$

这与curl命令行中的情况完全相同,其中您有:

'{ "author": "icingaadmin", "comment": " Working on it.", "notify": true, "filter": "host.name == {\"$1\} && service.name == {\"$2\}"" }'''

这里有很多引用问题,从结尾的'''开始,包括最后一个}之前的""。如果你想扩展这些变量,你需要把它们移到单引号之外。您可以这样做:

'"host.name == {"'"$1"'"} && ...'

在本例中,"$1"位于单引号的之外。或者,您可以这样做:

"\"host.name == {\"$1\"} ** ..."

这里我们只是在外部使用双引号,所以变量扩展正常工作,但是我们必须转义字符串内的每个文本"。在

使用第一个选项,-d的最后一个参数如下所示(“something”,因为我不熟悉icinga):

'{ "author": "icingaadmin", "comment": " Working on it.", "notify": true, "filter": "host.name == {"'"$1"'"} && service.name == {"'"$2"'"}}'

如果$1foo,而$2是{},则可以得到:

{ "author": "icingaadmin", "comment": " Working on it.", "notify": true, "filter": "host.name == {"foo"} && service.name == {"bar"}}

相关问题 更多 >