简体   繁体   中英

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 BC 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:

  • Client logs into server A and runs send.sh which will send the commands.

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

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' 

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.

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

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

call-servers-bc-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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM