Monday, September 17, 2012

Using Password Protected Keys in Linux with SSH-auth

Passwords are great until you have to type them over and over again. I recently started using SSH keys with GitHub and, like a good user, put a password on my private key. That unfortunately requires me to type my password far too often. Once would make me much happier so I decided to find a solution which will allow me to continue being lazy.

I use Pageant in Windows so I knew something existed - it was a matter of finding out how to set it up. A quick read of various GitHub help articles got me to the point where I could test my connection and verify it was using my key file (I'm assuming you've gotten this far as well).

ssh -vT

I saw the reference to ssh-agent and ssh-add and thought I had my solution. So I ran ssh-agent and then tried to add my key via ssh-add and received the following error:

Could not open a connection to your authentication agent.

Some time later, I found out that the stuff ssh-agent spits out when it starts up is important. Its actually commands you should run to set your environment variables. Ok: copy & paste, run ssh-add with my key, enter my password, and try to connect to GitHub.

Works! Wonderful - now that was too many steps. Again, chronic laziness needs to be maintained. You can eliminate the copy & paste by using:

eval `ssh-agent`

That will execute the echoed bits from ssh-agent. But, again, I really want this simple so I don't have to try to remember anything. So why not make a shell script to run both the ssh-agent and ssh-add commands? Well, that shell script will run in a separate process space and everything that happens there will not be in your process space when its done.

The solution is to use a shell function. Just add something like this to the bottom of your .bash_profile (or equivalent):

function authsshkey()
eval `ssh-agent`
ssh-add .ssh/id_rsa

Now, from the command line (after running . ~/.bash_profile to load the changes), type:


And you'll be prompted for you password. Now when you run:

ssh -vT

You won't be asked for your password. Each time you login to your shell, you'll need to run authsshkey to get your key into memory. However, its down to one short command and one time password entry and then you're free from all the extra typing while in that session.

Laziness restored!