OfficialRebound
OfficialRebound

Reputation: 1

Use Bash to send multiple SSH commands

This is a simple and quick question I need an answer to. I am OK at bash and know Java and C but would like to keep this extremely simple. Here is the goal: I log on as root on server A and would like to send a command to servers B C and D via SSH. I want it so that it will automatically log into the servers (with a password) and send a command to them, from server A to the other servers.

So it would go something like this:

How would I go about doing this in extremely simple bash? Thanks for any help.

Upvotes: 0

Views: 2174

Answers (3)

vastlysuperiorman
vastlysuperiorman

Reputation: 1784

I would recommend having a file that contains the list of servers the command will ssh to. Simply put one IP address or hostname per line in the file. I'll call it hosts.txt here. Then use a while loop to run the command over each connection. Make sure to add your public key to authorized_keys on each of the hosts.

command="echo test"
while read host
do
    ssh -i [your public key] root@${host} "${command}" < /dev/null
done < hosts.txt

If you want to send multiple successive commands to each server, use the "End of Transmission" character as follows (similar to end of file):

ssh -o options user@server << EOT
command1
command2
command3
EOT

All of the commands in the section surrounded by EOT will be run in succession.

Upvotes: 1

Gui Rava
Gui Rava

Reputation: 448

3 steps :

  1. install your public key on all 4 machines (a, b, c and d) . If you're using openssh, you need to append your public key to .ssh/authorized_keys (see OpenSSH) , if you're using dropbear it's a bit different.

    Step 1 is complete when you can log in to a , then from a to b, from a to c, and from a to d without any password prompt.

  2. Write your ~/send.sh script on a . Since authentication is taken care of, the script is as simple as this:

    ssh b 'some_command'
    ssh c 'some_other_command'
    ssh d 'yet_another_command'
    
  3. Run the ssh client from your machine :

    ssh a '~/send.sh'
    

Upvotes: 1

Vytenis Bivainis
Vytenis Bivainis

Reputation: 2366

Try filling file call-servers-b-c-and-d.sh in a and execute

ssh a ~/call-servers-b-c-and-d.sh

call-servers-b-c-and-d.sh could contain

ssh b command
ssh c command
ssh d command

You might also choose to use public key authentication and ssh-copy-id to avoid typing passwords.

Upvotes: 0

Related Questions