Is it possible to spawn an ssh-agent for a new tmux session?

I've seen lots of hacks for re-establishing contact with a GUI session's SSH agent from within tmux (and screen) sessions. I'm wondering if it's possible to de-couple from the GUI and spawn an ssh-agent purely for use within a given tmux session? Would the agent itself have to "use-up" one of the tmux windows to avoid getting killed or is it possible to spawn one in the background that persists as long as the session is alive?


Solution 1:

OK I've done some more digging around and I should be able to easily hook to whatever SSH_AGENT is around when the terminal is attached. tmux already provides the key configuration "update-environment" however the missing piece is existing shells are not magically updated. However tmux does track the environment variables updated so the update script is a lot less hacky than screens:


# Sync the environment of an existing shell
#
#  tmux already updates the environment according to
#  the update-environment settings in the config. However
#  for existing shells you need to sync from from tmux's view
#  of the world.
function tmux_sync_env
{
    external_env=`tmux showenv | grep -v "^-"`
    export ${external_env}
}

From this commit

Solution 2:

I had to modify @stsquad's answer. It was failing for me because the export command could not set the SSH_CONNECTION variable.

I had to wrap the value of SSH_CONNECTION in quotes.

function tmux_sync_env
{
    ssh_auth_sock=`tmux showenv | grep "^SSH_AUTH_SOCK"`
    ssh_connection=`tmux showenv | grep "^SSH_CONNECTION"`
    export ${ssh_auth_sock}
    export "${ssh_connection}"
}