Automatically Start ssh-agent on Mac OS X

Mac OS X does not automatically start ssh-agent for you when it creates a new login session.  I suppose this makes sense for much of the Mac target audience that will never use ssh, but it is annoying for those of us who use it regularly.

I added the following to my .profile automatically start ssh-agent when I open my first terminal window:

if [ "x" == "x`ps -x -u ${USER} | egrep [s]sh-agent`" ] ; then
	ssh-agent | sed -e "/^echo/d" > ${HOME}/bin/agent-env
fi
source ${HOME}/bin/agent-env

Terminal.app starts a new login shell, which calls .profile every time you create a new window.  The ‘if’ statement check so see if ssh-agent is already running, if not, it starts a new ssh-agent and writes the output to ${HOME}/bin/agent-env.

This file sets the environment variables ssh needs to find the ssh-agent.  The ‘source’ command after the if statement runs agent-env in the current process, which allows the environment variables to take effect in the current process.

You will still have to run ssh-add to add your keys, but at least you do not have to start the ssh-agent.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s