CURL API在Bash脚本中传递参数

时间:2017-09-04 15:54:31

标签: python linux curl icinga

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

我有一个curl命令并将其传递给Bash脚本,我需要在此方法的POST方法中有两个变量,如何将参数传递给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应分别有主机名和服务名

请帮忙

感谢 阿拉汶

1 个答案:

答案 0 :(得分:1)

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

$ echo '$DISPLAY'
$DISPLAY

使用:

$ echo "$DISPLAY"
:0

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

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

从最后的'''开始,实际上有很多引用问题,并且在最后""之前包括}。如果您希望扩展这些变量,则需要将它们移到单引号之外。你可以这样做:

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

在这种情况下,"$1"是单引号的。或者,您可以这样做:

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

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

使用第一个选项,-d的最终参数看起来像这样(“某事”,因为我不熟悉icinga):

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

如果$1foo$2bar,则会显示:

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