Quick Tips · January 19, 2022

Quickly push ssh keys to all your servers!

In this episode, I show you how to quickly and easily push your SSH public key out to a list of servers! This saves you a ton of time with repetitive logins, and is the preferred way to authenticate. Check out the video below, and come back for the example code after the break!

YouTube player

As you saw in the short video, you need two things: the script on your Mac or Linux machine…

#!/bin/bash
read -p 'Server username: ' uservar
read -sp 'Password: ' pwvar
for server in `cat list_of_servers`; do
    sshpass -p "${pwvar}" ssh-copy-id -i ~/.ssh/id_rsa.pub -o StrictHostKeyChecking=no "${uservar}@${server}"
done

… and the input file. The file is just named “list_of_servers” (with no file extension) and has each server on a new row, like this:

server01
server02
anotherserver.mydomain.com
192.168.0.100

Each server can be either a resolvable DNS name (server01), a fully-qualified name (anotherserver.mydomain.com) or just the IP address of the server will do as well (192.168.0.100)

Keep in mind, since this script is doing the key push in bulk, each server on this list needs to use the same username and password. It also does not do any harm to run the script a second or third time if you are just adding new servers to the list, it wont do anything bad.

Thanks for checking out this quick tip! Leave me a comment in the video description if you have questions, and as always I’ll see you in the next one!

~OMG