Adding Your Public Key to Lots of Servers

Problem

Your project is moving to public key authentication for SSH access, and you need to copy your key to a few dozen servers.

Solution

There are several scripts available to help automate the process, but they all do basically the same thing, which is ensure that a copy of your public key is appended to the ~/.ssh/authorized_keys2 file on the target.

The following simple bash script can be used to run an ssh command that will append the public key to the authorized_keys file located in ~/.ssh on the remote system:

#!/bin/sh

KEY="$HOME/.ssh/vieglais.dataone.org.rsa.4096.pub"
KEYDEST="~/.ssh/authorized_keys"

if [ ! -f ${KEY} ];then
    echo "Key not found at: $KEY"
    echo "Create it using something like: "
    echo "  ssh-keygen -t rsa -b 4096 \\"
    echo "    -C \"some useful comment\" \\"
    echo "    -f \"$USER.dataone.org.rsa.4096\""
    exit 1
fi

if [ -z $1 ]; then
    echo "Usage: upload_ssh_key user@host.name"
    exit 1
fi

echo "Installing key on $1... "
KEYCODE=$(cat ${KEY})
ssh -q $1 "mkdir ~/.ssh 2>/dev/null; chmod 700 ~/.ssh; echo "${KEYCODE}" >> ${KEYDEST}; chmod 644 ${KEYDEST}"
echo "done."

The input for the script is the server being targeted. Since there’s a bunch of those to work with, a bit more scripting can help:

$ for s in $(cat servers.txt); do upload_ssh_key $s; done

For this to work, servers.txt is a plain text file with each line in the file being a target server.