Friday, March 26, 2010

Enabling ssh-agent for password-less ssh login on KDE/Gnome

So one of the things that had been bothering me was ssh'ing into remote machines with keys that had passwords. I wanted to use ssh-agent so that I would not have to type in my password. Trouble was that I couldn't figure out how to do it on my KDE desktop so that every time I opened a new shell the ssh-agent would be active. Everything I'd previously read talked about executing the command:
  ssh-agent bash
...but this only starts the agent for the shell started and any child processes of that shell. Consequently, every shell opened has its own ssh-agent and you have to do a ssh-add on each shell, typing in your password each time.

Well here is how to do it

start-ssh-agent script

#!/bin/bash
if [ -f ~/.ssh/ssh-agent.env ]; then
  #echo "Agent already started"
  i=1
  #I just needed something above so the then was a valid statement
  #...is there a noop in bash?
else
  ssh-agent > ~/.ssh/ssh-agent.env
  #we need to delete the echo from the source script since some
  #commands like scp and ssh hate it when .cshrc echos stuff out
  sed -e '/echo/d' ~/.ssh/ssh-agent.env > ~/.ssh/ssh-agent2.env
  mv ~/.ssh/ssh-agent2.env ~/.ssh/ssh-agent.env
  . ~/.ssh/ssh-agent.env
  #echo "Agent started"
  ssh-add
fi

Basically this script executes ssh-agent, captures the output that specifies the environment variables and writes them to a file for future reference from future shells. It then executes ssh-add to prompt you to enter the passwords for the private keys.


stop-ssh-agent script

#!/bin/bash
if [ -f ~/.ssh/ssh-agent.env ]; then
  . ~/.ssh/ssh-agent.env > /dev/null
  kill $SSH_AGENT_PID
  rm ~/.ssh/ssh-agent.env
  echo "Agent stopped"
else
  echo "Agent is not running"
fi

Then in ~/.bashrc file you add the following:

if [ -f ~/.ssh/ssh-agent.env ]; then
        . ~/.ssh/ssh-agent.env
else
        ~/bin/start-ssh-agent
fi

...this basically means...
if the ssh-agent.env file exists
  source it so that the environment vars point to the ssh-agent process running.
else
  run the script to start the ssh-agent and prompt for the passwords for any keys

This is not perfect and you need to be careful if you are doing agent forwarding into the box but for most general cases this works.

No comments: