Question

I've got the following script snippit I've written and am using:

ssh -t root@$host bash -c "' echo \"Connected to server $host\" echo \"Paste in data and hit Ctrl + D\" data=$(cat) echo \"Success!\" echo $data '"

It works fine without the cat line and executes in order.

With the cat line, it hangs for input before any of the echos and then when you Ctrl + D it executes the rest.

How can I get this to run back in the intended order?

EDIT:

For clarity, I'm simply attempting to get data from the local console after making the SSH connection. If I was to use a read, this works fine and prompts. But if I use "$(cat)" (which works fine locally) I have issues.

I'm attempting to take multiple lines of text in after the SSH connection. I'm using $(cat) to do this as per link, which works fine locally but doesn't appear to work in remote commands via SSH.

Was it helpful?

Solution

The reason the cat happens at the start is because you are using double quotes. The $(cat) is evaluated and executed locally before the ssh command runs. To prevent that, use single quotes instead. (I took the liberty to simplify a bit more at the same time.)

ssh -t root@$host "echo 'Connected to server $host'"';
    echo "Paste in data and hit Ctrl + D"
    data=$(cat)
    echo "Success!"
    echo "$data"'

(The first echo is in double quotes in order to allow $host to be expanded locally; then we switch to single quotes to protect the rest of the command line from local expansion.)

OTHER TIPS

1- Using variables in ssh connection would be something like this:

while read pass port user ip fileinput fileoutput filetemp; do
     sshpass -p$pass ssh -o 'StrictHostKeyChecking no' -p $port $user@$ip fileinput=$fileinput fileoutput=$fileoutput filetemp=$filetemp 'bash -s'<<ENDSSH1
     python /path/to/f.py $fileinput $fileoutput $filetemp
     ENDSSH1
done  <<____HERE1
     PASS    PORT    USER    IP    FILE-INPUT    FILE-OUTPUT    FILE-TEMP
____HERE1

So you can change this script in the way you want.

2- Can't you change your script to this way?

ssh -t root@$host bash -c "'
   echo \"Connected to server $host\"
   echo \"Paste in data and hit Ctrl + D\"
   data=`cat <input-file>`
   echo \"Success!\"
   echo $data
'"

3- If you want to run some commands on remote machine try this one:

#!/bin/bash

SCRIPT='
<put your commands here>
'

while read pass ip; do
    sshpass -p$pass ssh -o 'StrictHostKeyChecking no' -p <port> root@$ip "$Script"
done <<HERE
pass1 ip1
pass2 ip2
pass3 ip3
  .    .
  .    .
  .    .
HERE
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top