Network management: Netomata – Single source, machine generated network configs Automatic MySQL backup with emails off-site and clean up
Aug 01

Whenever I start a new gig I have to key all the boxes – it’s tedious at best. Here’s a bash function to put a key on a far box. I always make sure I have an “eval `ssh-agent`” and “ssh-add” in my shell before running ‘keybox’.

Usage:
keybox [user@]box
Example:
keybox root@hammerforge

Warnings:
Uses ‘mktemp’ which might not be on every OS. Assumes a POSIXy shell at both ends. Tested with bash and zsh.


##############################
##########
# Thu May 28 13:57:25 2009
# will key a box for you
# use like "keybox foobar" OR "keybox user@foobar" it will take
# ~/.ssh/id_dsa.pub (change for your keytype) and write it to the far
# $USER/.ssh/authorized_keys file. Assumes you are using ssh-agent, ssh-add
# for passwdless logins.
#-Tony Thu May 28 16:59:22 2009

function keybox () {

# correct for your keytype
SSH_PUB_KEY=~/.ssh/id_dsa.pub
#SSH_PUB_KEY=~/.ssh/id_rsa.pub
###

# see is we got user@box, key the 'user' (ie root@hammerforge will
# have your key added to ~root/.ssh/authorized_Keys)
if (echo $1|grep -q @)
then
USER_TO_KEY=`echo $1|cut -f1 -d'@'`
MACHINE_TO_KEY=`echo $1|cut -f2 -d'@'`
else
USER_TO_KEY=$USER
MACHINE_TO_KEY=$1
fi

AUTH_KEYS=.ssh/authorized_keys
if [ -f ${SSH_PUB_KEY} ]
then
echo found ${SSH_PUB_KEY}
else
echo "did not file a public key, generating a new dsa key"
ssh-keygen -t dsa
echo
echo "continuing to keybox $MACHINE_TO_KEY"

fi
LOCAL_KEY=`cat ${SSH_PUB_KEY}`

TEMP_FILE=`mktemp -u`
# use some ssh options so it doesn't complain about known_hosts.
ssh -o StrictHostKeyChecking=no ${USER_TO_KEY}@${MACHINE_TO_KEY} "cp ~${USER_TO_KEY}/${AUTH_KEYS} ~${USER_TO_KEY}/.ssh/hold_authorized_keys ;echo \"$LOCAL_KEY\" > $TEMP_FILE ; cat $TEMP_FILE >> ~${USER_TO_KEY}/${AUTH_KEYS}"
# do another ssh to confirm you can get back to the box
# Batchmode causes ssh it quit if the autologin doesn't work
ssh -o BatchMode=yes ${USER_TO_KEY}@${MACHINE_TO_KEY} "hostname; date ; rm -v $TEMP_FILE"

}

written by admin \\ tags:


Leave a Reply

You must be logged in to post a comment.