Tuesday, 26 February 2013

Script to Install Public Key on Multiple Hosts

Here's a little script that can upload a public key onto a server - you could run it for multiple servers at the same time. Requires sshpass to be installed.

stty -echo
read -p "Password: " passw; echo
stty echo

public_key=`cat ~/.ssh/id_rsa.pub`

command="
mkdir -p ~/.ssh;
chmod og=,u=rwx ~/.ssh;
if [ ! -f ~/.ssh/authorized_keys ];
  then touch ~/.ssh/authorized_keys;
fi;
if ! grep -Fxq \"$public_key\" ~/.ssh/authorized_keys;
  then echo \"$public_key\" >> ~/.ssh/authorized_keys;
fi
"

function updateKey {
  sshpass -p $passw ssh -oLogLevel=Error -oStrictHostKeyChecking=no $1 $command
  if [ $? -eq 0 ]
    then echo "Updated key on $1"
  else
    echo "Failed to update key on $1"
  fi
}

updateKey myhostname

No comments:

Post a Comment