SSHKey Management Made Easy

I’ve been working with Linux for years now, and one of the main things you learn early on is that it’s better to use an SSHKey than it is to use a password. It gets confusing to some people (including myself), sometimes, where things are supposed to go to make it simple to do password-less entry into a server.

I started using this script in 2007 and have kept it around and use it regularly (whenever I need to log on to other servers other than my own). It was originally somewhere on the internet, and I’ve taken it and modified it further.

Make sure this script is executable. It won’t work on Windows since Microsoft still hasn’t introduced native SSH. But it will work on Mac OS X or Linux variants.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/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!"

It is invoked simply by typing:

1
ncc-1701$ ./do_sshkeys.sh sshuser@sshhost.tld

Clearly, substitute sshuser with your username and sshhost.tld with your IP address or servername. (Also, ncc-1701$ is my command prompt – don’t type that) You’ll have to enter the password the first time, then the script will take your DSA public key and place it in the appropriate place on the remote server. Logout and try logging in normally and, if all goes well, you’ll login without having to enter your password.