0

I have one script which reads hosts IP from /etc/hosts file, do ssh and update the passwords there for the given user. However, the script is closed after setting password for the first host and not able to set password for rest of the hosts. Please find below files-

/etc/hosts file-

172.x.x.x host1
172.x.x.x host2
172.x.x.x host3

Script I am using is as-

key=$1  
user=$2  
password=$3  
filename='/etc/hosts'  
while IFS= read -r line; do 
   IFS=' ' read -r -a array <<< $line
   ssh -i $key centos@${array[0]} "echo "$password" | sudo passwd $user --stdin"  
done <$filename

Script is simple. but it is getting closed after setting password for host1 from file. Does anyone has any idea, what I am missing?

0

3 Answers 3

2

By default ssh reads from stdin which is your input file.ssh consumes the rest of the file and your while loop terminates.So try using

       ssh -n 
Sign up to request clarification or add additional context in comments.

Comments

0

What is happening is that ssh is swallowing all of the standard input. The way to avoid that in general is to use a different file descriptor for your input, for example:

while IFS= read -u 9 -r line
do
    […]
done 9< "$filename"

However, this approach to changing authentication is really quite insecure, and I would strongly recommend moving to using public keys instead.

Comments

0

Using awk would help overcome any issues:

awk -v key=$1 -v usa=$2 -v pass=$3 '{system("ssh -i "key" centos@"$1" \"echo "pass" | sudo passwd "usa" --stdin\"")}' $filename

Assign you passed parameters as awk variables with -v and then use these to construct the ssh command to be executed with awk's system function

3 Comments

you have kept filename at the end. What significance it has?
Apologies, should be $filename
Apologies, I made a mistake setting up the pass variable. Try it now. Make sure that this is set up in a script with the filename variables set to /etc/hosts and 3 parameters passed for the key, username and password

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.