Menu Close

Mass Distribution Of SSH Keys Across Server Estate

This guide assumes that you have your SSH key on all the servers you need to access, and that you have a new key that needs to be distributed across these servers. If you don’t have your SSH key across your estate, please follow the SSH Bash Script -Copy ID guide on this blog.

Why would you need to distribute a new SSH Key? there are several reasons, but this is something I have to do when we have a new starter within my team at work, or if a Developer or system needs to access certain servers. The key you will need to have is the .pub key, the user generates this by running the following in their terminal, and will then find the file at ~/.ssh/id_rsa.pub (or something similar)

# ssh-keygen

Once you have the key, place it somewhere easy to access

No create a new file called sshaddkey.sh or something easy to remember, the command below will allow you to do this (change “path” to the path of the file). I prefer to use nano, but you could use vi, or whatever editor you prefer

# nano /path/sshaddkey.sh

Now simply copy and paste the code from below, and modify it to match your credentials and host details. I rename the key file, so I can keep track of who they belong to

HOSTS="
192.168.0.150
192.168.0.151
192.168.0.152
192.168.0.155
"
function update {
	ssh -oConnectTimeout=5 -oPubKeyAuthentication=yes -oStrictHostKeyChecking=no -oPasswordAuthentication=no USER@$1 "echo \"`cat ~/ssh-keys/jsmith.pub`\" >> .ssh/authorized_keys"
    echo "Closing connection to $HOST"
  

}

for HOST in $HOSTS; do
	echo $HOST
	update $HOST $1
done

Once saved, you will need to grant permissions to the file

# sudo chmod 766 /path/sshaddkey.sh

Ensure you have all your host names or IPs lists, you can add as many as you want, each on a new line

Now to run the code use navigate to the folder it’s in, and execute it using the commands below

# cd /path

# ./sshaddkey.sh

The script wil cycle through each of the IPs or host names in the list, adding the key to the “authorized_keys file for the designated account.

if you have multiple keys to add, you can place tham all in 1 file, with each key on a separate line, and give the file name in the script, this will then add them all in one go, saving you even more time.

As best practice, I advise to add a little text to show who the key is for, and the date added, and by who

####### Keys added 22/02/2020 by A Gordon #######

#### J Blogs - Dev
fake-key/kjdfkjhkjetiofoihn4wrlkjnoivdoi4

#### M Smith - SysAdmin
fake-key/ddocvueaoijtroiwjgoiogk;smglmign

#### Bob T Builder - QA
fake-key/dkjfheiuoihuefbubasfuhiuegfiufaa

################################################

1 Comment

Leave a Comment

%d bloggers like this: