kala kala - 1 year ago 66
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.

declare array=$(docker images)
sshpass -p 'password' ssh -t username@ << EOF
declare List=""
while read -r line; do
if [ -z $(docker images -q $line) ]; then
List="$List $line"
done <<< "$array"

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.

docker images |
sshpass -p 'password' ssh -t username@ '
  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"

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 |
    "$@" 'while read -r line; do          
        docker images -q "$line" | grep -q . || echo "$line"

Now you can call it for one or more hosts:

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