Best way to distribute users’s Public ssh Key to many hosts (no prompt password)

Lab information

For this lab, we will distribute the ssh public key of our main server, Ansible Master to two different servers. That way we will be able to connect via ssh from the Ansible Master to the other two nodes without asking us for the password.

  • Ansible Master: 192.168.152.135
  • Node1: 192.168.152.136
  • Node2: 192.168.152.137

1. Create a file with your password

Create pass.txt file and introduce the password of the user that is the owner of the public key, in my example the user is remote and its password is password1234. Save the file and exit.

[remote@ansible]$ vi pass.txt
password1234

2. Distribute the public key

To distribute the public key we are going to use sshpass and ssh-copy-id commands. To do that, execute the following commands:

for host in 192.168.152.136 192.168.152.137
do
sshpass -f pass.txt ssh-copy-id ${host}
done

Or in a single line:

for host in 192.168.152.136 192.168.152.137; do sshpass -f pass.txt ssh-copy-id ${host}; done

Result

How you can see in the output below, the public key is distributed correctly on all servers and you don’t need to enter your the password for each server. Is a complete automation.

/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/remote/.ssh/id_rsa.pub"
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.152.136'"
and check to make sure that only the key(s) you wanted were added.

/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/remote/.ssh/id_rsa.pub"
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.152.137'"
and check to make sure that only the key(s) you wanted were added.

Compartir:

This article was written by RoberMB

💻OS, ☁️Cloud, 🛡️Cybersecurity, ✈️Traveling ... ................ Always learning. 🏴‍☠️🏴‍☠️🏴‍☠️ CEH v10, CPHE, ICPP+(In progress) 🏴‍☠️🏴‍☠️🏴‍☠️

Leave a Reply

Your e-mail address will not be published. Required fields are marked *