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


  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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store