Distribute SSH keys easily

You know it can be cumbersome to copy over your public ssh-key to every server you have ever been to, so you push the action "automate ssh login" further and further into your personal planning.

Now it's time to distribute keys for once and for all. Let's use a script to speed things up a bit.

Update, check out ssh-copy-id(1). It does the same thing but is packaged with a openssh, far better than custom scripts! Thanks Davee

#!/bin/sh

# A script to push a key to the only argument, a remote server.

# Check if an argument was given.
if [ ! "$1" ] ; then
echo "Please specify a hostname to distribute the key to."
exit 1
fi

# Check if all the local files are here.
if [ ! -f ~/.ssh/id_rsa.pub ] ; then
echo "The local file ~/.ssh/id_rsa.pub is missing. Please create it."
exit 1
fi

# This command send the key, create a .ssh dir if required and set the
# correct permissions.
cat ~/.ssh/id_rsa.pub | ssh -q "$1" "if [ ! -d ~/.ssh/ ] ; then mkdir ~/.ssh ; fi ; chmod 700 ~/.ssh/ ; cat - >> ~/.ssh/authorized_keys ; chmod 600 ~/.ssh/authorized_keys"

What this script does it copy over your public ssh key to a server and set the permissions of the directories correct. This can be difficult from time to time.

The script will ask you once for your password on the remote server and do everything in that one session.

Here is how you could use the script:

$ ./ssh-push-key.sh server.example.com

Or if you have a list of server (extract them from ~/.ssh/known_hosts) you could use this list like this:

$ cat list-of-servers.txt | while read hostname ; do
>  ./ssh-push-key.sh "$hostname"
> done

Comments

How is this different from

How is this different from 'ssh-copy-id' which is already distributed with ssh?

Where? It doesn't seem to

Where? It doesn't seem to be included in the OpenSSH source.

I did not know that tool,

I did not know that tool, but thanks! I'll check it and update the story.

Robert de Bock
robert@meinit.nl

Thank you, I wish I thought

Thank you, I wish I thought of it.... I will be saving it for later use. =)
My only concern: just by quickly looking over the code, it appears to not deal with ssh login's that also require a passphrase

That is true, it will just

That is true, it will just ask for the password or passphrase. But there is no trick of skipping the password as there is not key installed on the remote box that matches the local one. The whole purpose of this script is to distribute a key. If you already have a key available and working, checkout this article: http://meinit.nl/enter-your-ssh-passphrase-once-use-it-many-times-even-f...

Regards,

Robert de Bock
robert@meinit.nl