Wednesday, July 18, 2012

Avoid duplicates in authorized_keys after ssh-copy-id

This is a question that comes up every so often and here is a proposal through which you can override any existing authorized ssh public key. I have used this POB recipe with Remoto-IT while configuring Hadoop Clusters:
#!/bin/bash -ex
# ssh-copy-id-uniq.sh

localUser=$1
remoteUser=$2
remoteHost=$3
publicKey=$4
privateKey=$5

LOCAL_HOST_NAME=`hostname`

USAGE="Usage: `basename $0` <localUser> <remoteUser> <remoteHost> <publicKey> <privateKey>"

if [ $# -ne "5" ] 
then
 echo $USAGE
  exit 1 
fi

su $localUser -c "ssh-copy-id -i $publicKey $remoteUser@$remoteHost"
ssh -i $privateKey $remoteUser@$remoteHost "sed -i \"\\\$!{/$user@$LOCAL_HOST_NAME/d;}\" ~/.ssh/authorized_keys"
The below command will then deploy the public key from one server (For example using Remoto-IT in the hadoop master server) in the remote server (in this case a hadoop slave server) and will use the private key to password-less login and delete all lines referring to the current host for the given user:
common/tools/ssh-copy-id-uniq.sh $HADOOP_USER $HADOOP_USER $SLAVE_HOSTNAME /home/$HADOOP_USER/.ssh/id_rsa.pub /home/$HADOOP_USER/.ssh/id_rsa

No comments:

Followers