【问题标题】:CURL API to pass parameters in Bash scriptCURL API 在 Bash 脚本中传递参数
【发布时间】:2018-02-12 21:38:29
【问题描述】:

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

我有一个 curl 命令并将其传递给 Bash 脚本,我需要在此 URL 的 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 应该分别有主机名和服务名

请帮忙

谢谢 阿拉文

【问题讨论】:

    标签: python linux curl icinga


    【解决方案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"}}
    

    【讨论】:

    • 我无法执行相同的操作,看起来转义序列仍然不起作用。
    • 失败的原因是什么?
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 2015-07-12
    • 2020-09-04
    • 2011-06-06
    • 2018-03-03
    • 2012-12-29
    • 2011-11-14
    • 2015-12-31
    相关资源
    最近更新 更多