How to ssh-copy-id multiple hosts using xargs and sshpass

How to ssh-copy-id multiple hosts using xargs and sshpass

How to ssh-copy-id multiple hosts using cat, xargs and sshpass

Imagine the following scenario: create ssh keys and copy the public key to 100 hosts!, ok this is a borring task but it can automated with an one-liner with the help of xargs and sshpass

Steps:

  1. Create a file with the hosts that you want to copy the public ssh key
  2. Install sshpass if needed
  3. With the following command you can deploy the public key to the list of hosts, change username and password to match your environment$ cat hosts.txt | xargs -t -I {} sshpass -p mypassword ssh-copy-id username@{}

A short explaination of the one-liner

cat hosts.txt : outputs host.txt content to xargs

xargs -t -I {}: -t prints the command that will executed, usefull for debug. -I {} advices xargs to replace {} with the content from hosts.txt

sshpass -p : wraps before an ssh command with a predefined password

ssh-copy-id: a script that copies the public key to a host, {} will be replaced by xargs with content from hosts.txt

$ ./buy-me-a-coffee ☕ // found this useful? I write these in my spare time