Setting a remote key through ssh


One of the steps I find myself doing a lot is distributing round an ssh key so that I can login and use different machines automatically. To help in that process I created a small function in my bash profile script (acutally for me it’s in .bash_aliases):

function setremotekey{ OLDDIR=`pwd` if [ -z "$1" ] then echo Need user@host info fi cd $HOME if [ -e "./.ssh/id_rsa.pub" ] then cat ./.ssh/id_rsa.pub |ssh $1 'mkdir -p -m 0700 .ssh && cat >> .ssh/authorized_keys' else ssh-keygen -t rsa cat ./.ssh/id_rsa.pub |ssh $1 'mkdir -p -m 0700 .ssh && cat >> .ssh/authorized_keys' fi cd $OLDDIR}

To use, whenever I want to copy my public key to a remote machine I just have to specify the login and machine:

$ setremotekey mc@narcissus

Then type in my password once, and the the function does the rest. How? Well it checks to make sure I’ve entered a user/host (or actually just a string of some kind). Then, if I haven’t created a public key before (which I might not have on a new machine), I run the ssh-keygen to create it. Once the key is in place, I output the key text and then use ssh to pipe append that to the remote authorized_keys file, creating the directory along the way if it doesn’t exist. Short and sweet, but saves me a lot of time.