Bash script on ssh multiple servers in loops and release commands

I have a text file in which I have a list of servers. I am trying to read the server one by one from a file, SSH on the server and execute ls to see the contents of the directory. My loop only works once when I run the SSH command, however for SCP it runs for all servers in a text file and ends, I want the loop to work until the end of the text file for SSH. Below is my bash script, how can I make it work for all servers in a text file by doing SSH ?

 #!/bin/bash while read line do name=$line ssh abc_def@ $line "hostname; ls;" # scp /home/zahaib/nodes/fpl_* abc_def@ $line:/home/abc_def/ done < $1 

I run the script as $ ./script.sh hostnames.txt

+6
source share
4 answers

The problem with this code is that ssh starts reading the data from stdin that you specified for read line . You can tell ssh to read from something else, such as /dev/null , so as not to use all other host names.

 #!/bin/bash while read line do ssh abc_def@ "$line" "hostname; ls;" < /dev/null done < "$1" 
+12
source

A little more straightforward is to use the -n flag, which tells ssh not to read from standard input.

+7
source

Change the loop to the for loop:

 for server in $(cat hostnames.txt); do # do your stuff here done 

It is not parallel ssh, but it works.

+2
source

I am opening a command line tool called Overcast to simplify this task.

First you import your servers:

 overcast import server.01 --ip=1.1.1.1 --ssh-key=/path/to/key overcast import server.02 --ip=1.1.1.2 --ssh-key=/path/to/key 

After that, you can run commands through them using wildcards, for example:

 overcast run server.* hostname "ls -Al" ./scriptfile overcast push server.* /home/zahaib/nodes/fpl_* /home/abc_def/ 
+1
source

Source: https://habr.com/ru/post/958967/


All Articles