Linux – ssh-agent and screen

command linegnu-screenlinuxssh-agent

A while back on StackOverflow, I asked this question about ssh-agent and crontab. I have a similar question now about ssh-agent and screen on linux systems.

So, on my Mac, ssh-agent launches at system startup, so it's always available to me. I think it would be true under my linux (redhat el5/fedora) if I were using X-Windows. However, this is a remote server machine and I'm always logging in via ssh.

I would love to have ssh-keys set up properly so I didn't have to enter my password multiple times during an svn update or commit. I'm happy to type in my passphrase once per session, and I discourage our team from having password-less ssh-keys.

For a brief shining moment, it seemed like doing "eval `ssh-agent -s`" in my .bash_profile, paired with a command to kill the ssh-agent when I logged out, would work. However, we make heavy use of screen in order to manage long-running interactive programs and development environments. If you start & stop ssh-agent as I just described, then it gets killed when you exit out of the terminal, and the screen's sub-sessions which used to be referring to that ssh-agent instance are abandoned.

So … how can I be a console user, who uses screen, who uses a password with his ssh-keys, who doesn't have to type in the passphrase constantly?

Best Answer

With the following setup, you won't need any wrapper for invoking screen. Moreover, it avoids using /tmp (with the consequent security risks).

  1. Ensure you have an ~/tmp directory:

    mkdir ~/tmp
    
  2. Add to .screenrc the following line:

    setenv SSH_AUTH_SOCK "$HOME/tmp/ssh-agent-screen"
    
    • This ensures that inside screen, ssh looks for the socket always in the same location, rather than a changing path.
    • You must use setenv whichever shell you use, since it's a screen and not a shell command.
  3. Add to .bash_profile the following line:

    [ -n "$SSH_AUTH_SOCK" ] && [ "$SSH_AUTH_SOCK"!="$HOME/tmp/ssh-agent-screen" ] && ln -sf "$SSH_AUTH_SOCK" "$HOME/tmp/ssh-agent-screen"
    
    • This will link from the fixed location (where ssh looks) to the real one, and must appear after starting ssh-agent.
    • Using [ -n "$SSH_AUTH_SOCK" ] will properly prevent errors when SSH_AUTH_SOCK is not set.
    • [ "$SSH_AUTH_SOCK"!="$HOME/tmp/ssh-agent-screen" ] will prevent screen sessions linking $HOME/tmp/ssh-agent-screen to itself, if screen sources .bash_profile.
  4. Instead of starting ssh-agent in .bash_profile, you can consider connecting with ssh -A (to use agent forwarding and make the remote machine use your agent).

After this setup, you can just use standard screen command. You'll only need to recreate existing sessions or manually set SSH_AUTH_SOCK inside them to the fixed location of step 2.

Credits to this website for the idea; I avoided using /tmp. This answer is similar but uses extra aliases.

Related Question