CyberKeeda In Social Media

BASH : Using while loop to ssh to multiple servers and run multiple commands



So today I got a requirement to perform some regular tasks to be executed on 100 Hosts.

These are the two task that i have to perform on 100 servers from SSH remote execution.

Create a Symbolic Link for a directory into User's directory
Give Ownership of the same Symbolic link.

Commands involved.
ln -s /home/BackUP_Data/  /home/user_directory
chown -R userid.gid  /home/user_directory/BackUP_Data

So it seems to be pretty simply , but here are two variables that I'm supposed to fetch out from two files.

/tmp/xyz_host.txt contains all 100 hostname
/tmp/xyz_user.txt conatins all 100 Users with respect to the same hostname in parralel to it.

Hence upon addition of variables from my files we have to execute something like below.

ssh root@$x " ln -s /home/BackUP_Data/  /home/$y  && chown -R userid.gid  /home/user_directory/BackUP_Data "
"

Task looks simple and i tried to use my old WHILE loop snippet to perform the same activity.

While Loop with Multiple Variables from multiple file as input

But somehow it didn't went well just after executing the commands into the first host , the loop stucks at all.

Somehow our common friend google is here and STACKexchnage is my best friend during scripting.

It somehow fixed me , just by adding  an extra   < /dev/null;


So overall the while loop will look like


while read -r x && read -r y <&3; do ssh root@$x " ln -s /home/BackUP_Data/  /home/$y  && chown -R userid.gid  /home/user_directory/BackUP_Data
" < /dev/null; done</tmp/xyz_host.txt 3</tmp/xyz_user.txt


The same has been briefly explained here as

ssh is reading the rest of your standard input.
while read HOST ; do … ; done < servers.txt
read reads from stdin. The < redirects stdin from a file.

Unfortunately, the command you're trying to run also reads stdin, so it winds up eating the rest of your file. You can see it clearly with

Explained well as Workaround / Solution for it by using SECOND Redirect
while read HOST ; do ssh $HOST "uname -a" < /dev/null; done < servers.txt

A detailed explanation can be found here ...  Stackexchange
Reference : Stackexchange









No comments:

Post a Comment

Designed By Jackuna