Home > other >  How to execute command under ssh remote machine and parse json value
How to execute command under ssh remote machine and parse json value

Time:11-23

I have a json format file where located on remote machine /tmp and its context as below

{
    "data": {
        "room.number": "1111",
        "name": "student",
        "phone": "1234-5678"
    },
    "type": "XXX",
    "car": "toyota"
}

I use following commands connect to remote and try to parse the value. I can get name's value but cannot get room.number value successfully.

When I run command on remote machine terminal directly, both commands are work.

root@remote-machine:/tmp# jq -r '.data.name' /tmp/ca.json.1
student

root@remote-machine:/tmp# jq -r '.data."room.number"' /tmp/ca.json.1
1111

Back to my local machine, the room.number is null

root@local-machine:~# ssh -o "StrictHostKeyChecking=no" -i /root/.ssh/id_rsa $ACCOUNT@$TARGET_IP -t 'sudo su - -c "jq -r '.data.name' /tmp/ca.json.1"'
student

root@local-machine:~# ssh -o "StrictHostKeyChecking=no" -i /root/.ssh/id_rsa $ACCOUNT@$TARGET_IP -t 'sudo su - -c "jq -r '.data."room.number"' /tmp/ca.json.1"'
null

How should I modify my command and then I can get room.number value?

CodePudding user response:

You can achieve this as follows:

ssh -o "StrictHostKeyChecking=no" -i /root/.ssh/id_rsa $ACCOUNT@$TARGET_IP -t "sudo su - -c \"jq -r '.data.\\\"room.number\\\"' /tmp/ca.json.1\""

Explanation

Initially we have the following command

ssh [other-flags] -t "sudo su - -c \"jq -r '.data.\\\"room.number\\\"' /tmp/ca.json.1\""

So ssh invokes command in double quotes and replace all the escape characters. Hence \" changes to " and \\ changes to \. So the internal command which will execute will look like:

sudo su - -c "jq -r '.data.\"room.number\"' /tmp/ca.json.1"

Now again sudo invokes command in double quotes and so escape characters are again replaced: \" changes to " and the final executing command becomes:

jq -r '.data."room.number"' /tmp/ca.json.1

Which is exactly the needed command we would like to execute!

  • Related