How-to: Authorize SSL keys w/o duplicating
September 29, 2009
When authorizing SSL keys, you typically concatenate it to the
authorized_keys file. Like this:
cat publickey.pub >> ~/.ssh/authorized_keysBut this simple method doesn't work when you're trying to load keys automatically .The keys might already exist, and if you keep concatenating the file,
authorized_keys will get miles long with duplicates. So, here's a basic bash script to authorize a key if it doesn't already exist in the index:
#!/bin/bash
keypub="/root/github.pub"
keyprivate="/root/github"
while read line; do
keydata=$line
done < $keypub
keydata="${keydata#"${keydata%%[![:space:]]*}"}"
keydata="${keydata%"${keydata##*[![:space:]]}"}"
keyfound=`fgrep "${keydata}" ~/.ssh/authorized_keys`
if [[ -n "${keyfound}" ]]; then
echo "${keydata}"
echo "SSH key already loaded into ~/.ssh/authorized_keys"
exit 1
else
keypubname=`basename $keypub`
keyprivatename=`basename $keyprivate`
sudo cp -f "$keyprivate" "/root/.ssh/${keyprivatename}"
sudo cp -f "$keypub" "/root/.ssh/${keypubname}"
sudo cat "/root/.ssh/${keypubname}" >> "/root/.ssh/authorized_keys"
echo "${keydata}"
echo "Key successfully loaded into ~/.ssh/authorized_keys"
exit 0
fi
Update these values to point to the public/private keys:
keypub="/root/github.pub" keyprivate="/root/github"Bash is beautiful for automation, isn't it?
The Commentary
Quick, be the first to comment!