mahmood
mahmood

Reputation: 24705

bash script to ssh and run commands

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

Upvotes: 1

Views: 13151

Answers (3)

d1jhoni1b
d1jhoni1b

Reputation: 8025

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="[email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]"
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

Upvotes: 1

user6077173
user6077173

Reputation:

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

Upvotes: 3

Avihoo Mamka
Avihoo Mamka

Reputation: 4786

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.

Upvotes: 1

Related Questions