【问题标题】:cURL read external variablecURL 读取外部变量
【发布时间】:2020-05-12 06:28:09
【问题描述】:

我在将变量推送到 bash 脚本以进行 cURL 询问时遇到问题
我正在使用此命令生成 api 令牌并将令牌粘贴到文件中:
curl -k -v -X POST --user admin:pass https://10.10.10.10/api/fmc_platform/v1/auth/generatetoken |& egrep -i '(X-auth|error)' | sed 's/.*X/X/' | grep 访问令牌 | awk '{print $2}' >token.file

token.file 的结果如下所示:237c3364-228a-475f-bf74-3b6822b53a31
我创建了一个从 token.file 读取令牌的变量:export tokenkey=$(cat token.file)

此令牌稍后将用于 GET/POST/PUSH,但我无法将其推送到 cURL。
一个例子是:
curl -k -X GET "https://10.10.10.10/api/fmc_config/v1/domain/xxxx/devices/devicerecords" -H "accept: application/json" -H "X-auth-access-token "${tokenkey}""

我收到此错误:{"error":{"category":"FRAMEWORK","messages":[{"description":"Access token not found"}],"severity":"ERROR"}}

它似乎没有正确读取变量。 我不确定如何在 curl 中定义变量以便正确读取令牌。

【问题讨论】:

    标签: curl


    【解决方案1】:

    不,没有证据表明它没有正确读取变量。有证据表明您没有遵循 curl 选项和 shell 语法的规范。

    首先,HTTP 标头的语法,主要在 curl 中使用-H/--header 指定,在标头名称和值之间需要一个冒号。您对-H "accept: application/json" 正确执行了此操作,但对-H "X-auth-access-token ... 却未正确执行此操作。诚然,通过给出错误消息而不是仅仅忽略坏项目,curl 可能会更有帮助。

    其次,您似乎正试图在标头值中包含双引号,这是 HTTP 中 some 标头值或部分所必需的,但您使用的语法无法实现这一点。

    -H "X-auth-access-token "${tokenkey}""
    #                       ^           ^ these marks are NOT part of the data
    #  ^--------------------^ instead this part is quoted _to the shell_ 
    #                        ^---------^ this is NOT quoted, which for a variable value
    #                                    is USUALLY unsafe, but for THIS value works
    #                                   ^^ and this is quoted, but empty
    

    对于这个(UUID 格式)值,您实际上不需要在标头中发送引号,但是当您确实需要或想要它们时,您应该使用

    -H "X-auth-access-token: \"${tokenkey}\""
    # this sends the name WITH the colon, then the value WITH quotemarks around it
    

    仅供参考,您在第一个命令中从响应中解析令牌的过程可能要简单得多,但您没有问过这个问题(或提供需要的示例数据)

    【讨论】:

    • 你是对的,这是正确的语法:X-auth-access-token: 而且我不需要引号。更正后,一切正常。
    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多