0
#!/bin/bash
hostnames='admin node1 node2 node3'
passwords='1234 1235 1236 1237'
for i in $hostnames
do
  for j in $passwords
  do
    sshpass -p $j  ssh-copy-id root@$i -p 22
  done
done

While running this script I realized that every element from host-names is tried with passwords.

How can I make it so that the first element from host-names matches with the first element from passwords then 2nd element with 2nd element and so on instead of matching each element from host-names to every element from passwords?

Also is it possible to fetch host-names and passwords from a file instead of declaring them like i did in my code?

Biffen
  • 6,249
  • 6
  • 28
  • 36
esh9999
  • 3
  • 1
  • 2

1 Answers1

0

Use arrays, and iterate over the indices rather than the elements.

hostnames=(admin node1 node2 node3)
passwords=(1234 1235 1236 1237)

for i in "${!hostnames[@]}"; do
    sshpass -p "${passwords[i]}" ssh-copy-id root@"${hostnames[i]}" -p 22
done

Or, similar to the suggestion by Biffen in a comment:

while read -r host password; do
    sshpass -p "$password" ssh-copy-id root@"$hostname" -p 22
done <<EOF
admin 1234
node1 1235
node2 1236
node3 1237
EOF
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thank you very much for helping me chepner. If possible could you please help me out with this: I stored 5 host-names and passwords in a file in two columns 1st column for host-name and the second for password(hostname password) if I store each column into a separate array like one array with host-names and another with passwords. Is it possible to refer to those arrays from the script. If not could you guide me as to how I might be able to fetch the host-names and passwords from the file, Instead of mentioning them in the script like I did above. Thank You very much in advance for help. – esh9999 Jun 03 '21 at 13:28