1

I want to ssh to a node and run a command there and then exit. This is repeated for all nods. The script is fairly simple

#!/bin/bash
NODES="compute-0-0 compute-0-1 compute-0-2 compute-0-3"
for i in $NODES
do
   ssh $i
   ls -l /share/apps 
   rpm -ivh /share/apps/file.rpm
   exit
done

But the problem is that, after the ssh, the ls -l command is missed. Therefore, the command prompt waits for an input!

Any way to fix that?

UPDATE:

I modified the loop body as

ssh $i <<END
 ls -l /share/apps
 exit
END

But I get

./lst.sh: line 9: warning: here-document at line 5 delimited by end-of-file (wanted `END')
./lst.sh: line 10: syntax error: unexpected end of file
mahmood
  • 23,197
  • 49
  • 147
  • 242
  • 2
    See http://stackoverflow.com/questions/37586811/pass-commands-as-input-to-another-command-su-ssh-sh-etc – Leon Jul 07 '16 at 07:40
  • If you want your `ssh` section of the script to be indented, use `<<-END` – Leon Jul 07 '16 at 07:54
  • 1
    The answer you accepted should work. However, your here-doc approach was not wrong either. I think, you have added some spaces before `END` after the `exit` line. Alternately, if you wnt those spaces for indentation, change the heredoc line to `ssh $i <<-END` (Notice the `<<-` operator instead of `<<`) – anishsane Jul 07 '16 at 07:54

3 Answers3

3

Try this

    #!/bin/bash
    NODES="compute-0-0 compute-0-1 compute-0-2 compute-0-3"
    for i in $NODES
    do
       ssh $i "ls -l /share/apps;rpm -ivh /share/apps/file.rpm;exit;"
    done
  • NODES should be an array, not a string. `nodes=( compute-0-{0,1,2,3} )`, then `for i in "${nodes[@]}"; do` -- that way you're not depending on string-splitting on IFS. – Charles Duffy Mar 20 '22 at 23:51
1

I'd change the script and would run the ssh command with the the command to execute.

For example:

#!/bin/bash
NODES="compute-0-0 compute-0-1 compute-0-2 compute-0-3"
for i in $NODES
do
   ssh $i "ls -l /share/apps && rpm -ivh /share/apps/file.rpm && exit"
done

The && operator means that each command will be executed only if the previous command succeeded.

If you want to run the command independently, you can change the && operator to ; instead.

Avihoo Mamka
  • 4,656
  • 3
  • 31
  • 44
1

identation is everything in this type of scripts, one sample bash script for sshing into different servers and exec actions on them:

#!/bin/bash
NODES="user@prod-work01.server.com user@prod-work02.server.com user@prod-work03.server.com user@prod-work04.server.com user@prod-work05.server.com user@prod-work06.server.com user@prod-work07.server.com user@prod-work08.server.com"
for i in $NODES
do
  echo "SSHing..."
  echo $i
ssh $i << EOF
  cd /home/user/server.com/current/
  bundle exec eye stop all
  echo "Some Process Stopped Successfully!"
EOF

done
d1jhoni1b
  • 7,497
  • 1
  • 51
  • 37