linux – Imaginary Billboards http://www.imaginarybillboards.com Imagined things Thu, 28 Jan 2010 02:09:27 +0000 en-US hourly 1 https://wordpress.org/?v=6.0.11 Lazy automatic ssh + key distribution http://www.imaginarybillboards.com/?p=74 http://www.imaginarybillboards.com/?p=74#respond Tue, 26 Jan 2010 21:00:53 +0000 http://www.imaginarybillboards.com/?p=74 I want to ssh to hosts, sometimes as a user, sometimes as root.  I also want to distribute my public ssh key so I don’t have to login anymore.  I want to do it without stacking tons of my keys onto the ends of files, and I want to be lazy about it.  This is the script I use, I put it somewhere in my path as “go” with chmod +x so it’s executable.  I can then use it like “go hostname” or “go chris@somehost”.

#!/usr/bin/env  bash
#this will copy our public key to a remote host and ssh to it.

userhost=
keyfile=~/.ssh/id_rsa.pub
authkeyfile='~/.ssh/authorized_keys'

#if no username is passed (like someuser@somehost), use root by default
if [[ ! "$userhost" =~ '@' ]]
  then
    userhost=root@
fi

#if no ssh public key exists, create one in the default spot
if [ ! -e $keyfile ]
  then
    echo "Creating SSH key in $keyfile"
    ssh-keygen -t rsa  -f $keyfile -q -N ''
fi
#now get the key itself into a variable
mypubkey=`cat $keyfile`

#this keeps it to one time needed to enter the password,
#it'll create the .ssh directory with right perms, touch the key file,
#create a backup without our key (no dupes),
#and copy it back
ssh $userhost "mkdir -p .ssh;
  chmod 700 .ssh;
  touch $authkeyfile;
  cp $authkeyfile ${authkeyfile}.bak;
  grep -v '$mypubkey' ${authkeyfile}.bak > $authkeyfile;
  echo '$mypubkey' >> $authkeyfile"

#and finally, ssh to the host.
ssh $userhost
]]>
http://www.imaginarybillboards.com/?feed=rss2&p=74 0