diceline-chartmagnifiermouse-upquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

Automatically add and remove SSH keys from remote hosts

Managing multiple hosts is a pain when using SSH key authentication. There are a lot of solutions out there for managing SSH keys, there's Ansible, Puppet, or other paid solutions.

There's also another option, to use a script to do the job for you.

Here's how

1. Create a targets file containing your hosts and usernames

# Host
hostname.example.com username

2. Create a add-keys.sh file

#!/bin/bash
keys=${1:-*.pub}
echo update ssh-keys: ${keys}

cat targets | grep -vE '^(\s*$|#)' | sed 's/#.*$//g' | while read host user
do
   echo "# Adding public ssh-keys for $user@$host"
   for k in ${keys};
   do
      echo "# Adding public key $k"
      touch ${k%\.pub}
      ssh-copy-id -f -i $k $user@$host
   done
done

3. Create a remove-keys.sh file


#!/bin/bash

keys=${1:-*.pub}
echo update ssh-keys: ${keys}

cat targets | grep -vE '^(\s*$|#)' | sed 's/#.*$//g' | while read host user
do
   echo "# Remove public ssh-keys for $user@$host"
   for k in ${keys};
   do
      echo "# Remove public key $k"
      key=$(<$k)
      ssh $user@$host 'bash -s' <<EOT
sed -i "/$key/d" ~/.ssh/authorized_keys
EOT
      echo "# Key removed"
   done
done

4. Add the public keys you want to add as .pub files in the same folder

5. Run one of the scripts. Done.