Copy SSH key to multiple hosts

I had a situation where I had 40 hosts to copy an ssh key to. A single one-liner command does the trick and makes this a trivial task.

First, create a text file with a list of all the hosts you wish to copy the key to. One line per entry. Call it keydeploy.txt. Then execute the bash line below:

cat keydeploy.txt | xargs -t -I {} sshpass -p p@ssw0rd ssh-copy-id -i ~/.ssh/ansible root@{}

A short explanation of the one-liner:

  1. cat keydeploy.txt: outputs keydeploy.txt content to xargs
  2. xargs -t -I {}: -t prints the command that will be executed, useful for debug. -I {} causes xargs to replace {} with the content from hosts.txt
  3. sshpass -p : wraps before an ssh command with a predefined password
  4. ssh-copy-id: a script that copies the public key to a host, {} will be replaced by xargs with content from hosts.txt

If you wish to copy keys to hosts in a series, then you could also do (where hostname is web1-40.prod):

for h in web{1..40}.prod; do echo $h | xargs -t -I {} sshpass -p P@ssw0rd ssh-copy-id -i ~/.ssh/ansible root@{}; done

I hope this helps you, and if it does, leave a comment! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *