0

I am using curl to create a session to log into the switch. Below the script that i use

curl --noproxy 10.23.193.1 -X POST http://10.23.193.1:80/rest/v3/login-sessions -d '{"userName":"admin", "password":"password"}'

After this is executed I get the following output

{"uri":"/login-sessions","cookie":"sessionId=DfZNCFbfoc3LDuMgjLXRiS8ZmEo4MWENCOJM0Iu14R1uMT9kKqbe1Rx6AedmoeT"}

My requirement here is to first only print this part of the string "sessionId=DfZNCFbfoc3LDuMgjLXRiS8ZmEo4MWENCOJM0Iu14R1uMT9kKqbe1Rx6AedmoeT"

Secondly I would want to know how to store the above string in a variable so that I could call the same variable for subsequent operations

I ran the following, but I am not getting any output.

curl --noproxy 10.23.193.1 -X POST http://10.23.193.1:80/rest/v3/login-sessions -d '{"userName":"admin", "password":"password"}' | grep -`E ""cookie":"
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Neil Roy
  • 17
  • 5

1 Answers1

2

Avoid using simple tools like grep or sed to parse JSON as they won't handle things like quotes or multi-line data correctly. It's best to use a JSON-aware program such as jq.

With jq it's simple and robust:

curl ... | jq '.cookie'

To store the cookie in a variable use the -r flag to have JQ print out the raw, unquoted string.

cookie=$(curl ... | jq -r '.cookie')

Further reading:

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thank you very much. You are awesome. Will figure out a way to install jq and go from there. Thank you loads – Neil Roy Jan 08 '20 at 13:29