snex
snex

Reputation: 1012

ssh bash receive variable from a remote file

I need to read the variable from a remote file over SSH and compare it. But I get a variable in the wrong format. how to do it correctly?

    #!/bin/bash 
    pass='dpassspass'
    user='[email protected]'
    IP="10.2.1.41"
    path=/sys/variable/serv
    #not work## No such file or directory# write=$(sshpass -p $ovhpass ssh -t $user echo "$IP" > $path)
    sshpass -p $pass ssh -t $user  << EOF
    echo "$IP" > $path
    EOF
    my_var=$(sshpass -p $pass ssh -t $user "cd /sys_ovh; ./serv.bash")
    echo mystart-"$my_var"-myend
    read=$(sshpass -p $pass ssh -t $user cat $path)
    echo start-"$read"-end
    echo start-"$IP"-end
    if [ "$read" == "$IP" ]; then 
    echo "run"
    fi

output:

Connection to 10.10.19.18 closed.
-myendt-10.2.1.41
Connection to 10.10.19.18 closed.
-endt-10.2.1.41
start-10.2.1.41-end

Where I make a mistake? How to take data from the SSH?

Upvotes: 1

Views: 1250

Answers (2)

tripleee
tripleee

Reputation: 189397

Your fundamental problem comes from using unquoted here documents for the commands. You should properly understand in which order the shell interprets these contructs.

ssh remote cmd >file

executes cmd remotely, but first redirects the output from the ssh command to the local file.

ssh remote "cmd >’$file'"

The quotes cause the redirection to be part of the remote command line. The variable file is interpreted first, by the local shell, though.

ssh remote 'cmd >"$file"`

The single quotes prevent the local shell from modifying the command before sending it. Thus, he variable interpolation and the redirection are both handled by the remote shell, in this order.

So your commented-out "not work" command could easily be fixed with proper quoting. However, it will be much more elegant and efficient to use a single remote session, and execute all the commands in one go. Mixing the local variable IP with remote variables calls for some rather elaborate escaping, though. A major simplification would be to pass the value on standard input, so that the entire remote script can be single quoted.

#!/bin/bash 
pass='dpassspass'
user='[email protected]'
IP="10.2.1.41"
result=$(echo "$IP" |
  sshpass -p "$pass" ssh -t "$user" '
    path=/sys/variable/serv
    cat > "$path"
    cd /sys_ovh
    ./serv.bash
    cat "$path"')
echo mystart-"${result%$'\n'*}"-myend
echo start-"${result#*$'\n'}"-end
echo start-"$IP"-end
if [ "${result#*$'\n'}" == "$IP" ]; then 
  echo "run"
fi

The output from the remote shell is two lines; we pick it apart by using the shell's prefix and suffix substitution operators.

Upvotes: 1

Walter A
Walter A

Reputation: 20002

The vars my_var and read are filled with a string ending with '\r', telling echo to go back to the first column. I think this is a problem with your local script. You can correct that with

tr -d "\r" < myfile > myfile2

Upvotes: 2

Related Questions