kala kala - 1 year ago 76
Bash Question

How to execute multiple commands on remote server and get the output?

I have a requirement to execute some commands on remote machine and i have written script like this on my local machine.


Basically i'm getting

docker images
on my local machine and want to check whether those images are existing in remote server or not.


I need to get non existing docker images (remote server) to my local machine. For that i have used below mentioned code, but it didn't work for me.

#!/bin/sh
declare array=$(docker images)
sshpass -p 'password' ssh -t [email protected] << EOF
declare List=""
while read -r line; do
if [ -z $(docker images -q $line) ]; then
List="$List $line"
else
continue
fi
done <<< "$array"
EOF


I want List variable to be in my local machine.

Can anyone help me on this issue?

Your help is much appreciated.

Best Regards.

Answer Source

Nothing you do in the remote shell will be present in your local shell once the remote shell exits. What you can do is have the remote shell print output and capture that.

By the by, you can't use arrays in a /bin/sh script, but we don't actually need arrays here.

#!/bin/sh
docker images |
sshpass -p 'password' ssh -t [email protected] '
  while read -r line; do
    # Suction: docker images -q image should return nonzero exit status
    # if the named image is missing.  We work around that by grepping
    # for whether there is any output at all.
    docker images -q "$line" | grep -q . || echo "$line"
  done'

This just prints out the result; capture that into a variable or redirect it to a file in order to do something more with it, or just pipe it into another local while read -r loop.

If you refactor this so that e.g. the authentication details are parametrized, you can run it against a number of hosts. You could save it as an executable script so you can call it from any other tool, or as a function if you just need it in a limited context.

missing () {
    docker images -q |
    "[email protected]" 'while read -r line; do          
        docker images -q "$line" | grep -q . || echo "$line"
    done'
}

Now you can call it for one or more hosts:

missing sshpass -p 'password' ssh -t [email protected] |
xargs -r -n 1 docker pull
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download