从 curl 请求中提取令牌并在另一个 shell 命令中使用

raz*_*aze 5 bash json curl

我已经开始学习 bash 脚本,但我一直在努力解决一些问题。

我有一个输出令牌的 curl 命令,我需要在以下命令中使用它:

curl -k 'https://server:port/session' -X POST -H 'Content-Type: application/json' -d '{"username":"admin","password":"password"}'
Run Code Online (Sandbox Code Playgroud)

然后它在这里输出一个令牌:

{"token":"ac07098ad59ca6f3fccea0e2a2f6cb080df55c9a52fc9d65"}
Run Code Online (Sandbox Code Playgroud)

然后我需要在后续命令中使用它

curl https://server:port/ -k -X POST -H 'Content-Type: application/json' -H 'X-Cookie:token=token' -d '
Run Code Online (Sandbox Code Playgroud)

我想我可以将令牌输出到文件,然后让 sed 命令将令牌写入文件,然后新命令使用变量 where token=$token

谢谢!

gle*_*man 10

这是 JSON 解析工具派上用场的地方(例如):

$ echo '{"token":"ac07098ad59ca6f3fccea0e2a2f6cb080df55c9a52fc9d65"}' | jq -r .token
ac07098ad59ca6f3fccea0e2a2f6cb080df55c9a52fc9d65
Run Code Online (Sandbox Code Playgroud)

所以

json=$( curl -k 'https://server:port/session' -X POST -H 'Content-Type: application/json' -d '{"username":"admin","password":"password"}' )
token=$( jq -r ".token" <<<"$json" )

curl https://server:port/ -k -X POST -H "X-Cookie:token=$token" ...
Run Code Online (Sandbox Code Playgroud)


tei*_*tel 7

除了 bash(已测试 Centos/Rhel7/GitBash)之外,没有其他工具:

json=$(curl -k 'https://server:port/session' \
            -X POST -H 'Content-Type: application/json' \
            -d '{"username":"admin","password":"password"}') \
&& token=$(echo $json | sed "s/{.*\"token\":\"\([^\"]*\).*}/\1/g") \
&& echo "token = $token"
Run Code Online (Sandbox Code Playgroud)

然后使用您的身份验证需要这样的命令:

curl https://server:port/ -k -X POST \
                          -H 'Content-Type: application/json' \
                          -H 'X-Cookie:token=$token' -d ...'
Run Code Online (Sandbox Code Playgroud)


Ben*_*min -2

使用 `` 语法:

cmd1result=$(command1 | cut -d ':' -f 2 | grep -Po "[a-z0-9-]+")
command2 $cmd1result
Run Code Online (Sandbox Code Playgroud)