How to bulk add an ssh key to multiple servers

If you need to add a colleague’s ssh key to multiple servers that share a similar name, you can do it with a simple one liner. In this post I will show you how.

Assuming the servers you need to add they key to are called:

server1.example.com
server2.example.com
server3.example.com
server4.example.com
etc…

And your colleagues key is in a file called key.pub

To add to a list of consecutive servers, use:

for i in {1..10}; do ssh-copy-id -i key.pub root@server$i.example.com; done

If you wanted to list specific servers, you could use:

for i in {1,4,7,10}; do ssh-copy-id -i key.pub root@server$i.example.com; done

You can then check it worked with the following: (replace colleagues-key-comment with the comment that identifies their public key):

for i in {1..14}; do echo server$i; ssh root@server$i.example.com cat /root/.ssh/authorized_keys | grep colleagues-key-comment; done

Leave a Reply

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