Skip to content

Instantly share code, notes, and snippets.

@withakay
Created December 11, 2017 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save withakay/1826494b032cdf07eb85bc845e3ff003 to your computer and use it in GitHub Desktop.
Save withakay/1826494b032cdf07eb85bc845e3ff003 to your computer and use it in GitHub Desktop.
Update authorized keys on remote server using known_hosts
#!/usr/bin/env bash
# Before running remember to generate a new key and update this script with the name (currently id_rsa_4096.pub)
awk -F'[ ,:]' '/^[0-9a-zA-Z]/{sub(/\[/,"",$1); sub(/\]/,"",$1); print $1}' ~/.ssh/known_hosts | uniq > _hosts
# A script to push a key to the only argument, a remote server.
while read h; do
echo "$h"
# Check if an argument was given.
if [ ! "$h" ] ; then
echo "Please specify a hostname to distribute the key to."
exit 1
fi
# Check if all the local files are here.
if [ ! -f ~/.ssh/id_rsa_4096.pub ] ; then
echo "The local file ~/.ssh/id_rsa_4096.pub is missing!"
exit 1
fi
# This command sends the key, create a .ssh dir if required and set the
# correct permissions.
cat ~/.ssh/id_rsa_4096.pub | ssh -l jack -o StrictHostKeyChecking=no -o ConnectTimeout=5 $h "if [ ! -d ~/.ssh/ ] ; then mkdir ~/.ssh ; fi ; chmod 700 ~/.ssh/ ; cat - >> ~/.ssh/authorized_keys ; chmod 600 ~/.ssh/authorized_keys"
done <_hosts
rm _hosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment