A shell script to upload SSH keys to remote machines

Sep 19, '07 07:30:00AM

Contributed by: devros

This is a script that I initially found online and have modified to be a bit more useful. Basically it automates the process of uploading your SSH key to a remote host that you SSH into by doing the following:

  1. Creates a .ssh directory if there is not one already there, and sets the correct permissions on it.
  2. Puts your key in the authorized_keys file (and creates it if it was not there already), and changes the permissions on it.
Here's the code:

#!/bin/sh

KEY="$HOME/.ssh/id_dsa.pub"

if [ ! -f ~/.ssh/id_dsa.pub ];then
    echo "private key not found at $KEY"
    echo "* please create it with "ssh-keygen -t dsa" *"
    echo "* to login to the remote host without a password, don't give the key you create with ssh-keygen a password! *"
    exit
fi

if [ -z $1 ];then
    echo "Please specify user@host.tld as the first switch to this script"
    exit
fi

echo "Putting your key on $1... "

KEYCODE=`cat $KEY`
ssh -q $1 "mkdir ~/.ssh 2>/dev/null; chmod 700 ~/.ssh; echo "$KEYCODE" >> ~/.ssh/authorized_keys; chmod 644 ~/.ssh/authorized_keys"

echo "done!"

If you SSH into many machines, the script can save you a lot of manual work.

[robg adds: I tested this, and it works as described -- I edited it to reflect the fact that I have an RSA key, not a DSA key (so I just changed id_dsa.pub to id_rsa.pub). When you run the script, you'll be prompted for the password on the remote machine; after it runs, you can connect without a password (if you're not using a passphrase).]

Comments (15)


Mac OS X Hints
http://hints.macworld.com/article.php?story=2007091814022049