I am an avid user of ssh-agent and screen. I ran into a problem recently where when I re-attached to an existing screen session, ssh-agent wasn't working even though I had used ssh -A to get to the box.
The reason is that the environment variables that ssh-agent uses to manage itself are created at login time, and thus an existing screen session has copies of those variables from a previous ssh session (the one when screen was started), and the SSH_AUTH_SOCK for the current ssh session is no longer the same as it was when screen was originally started.
Some googling brought me to this page, but that blog post is a little off for a couple of reasons. It was a great starting point, though, and I have now perfected that technique.
Here's all you need to do:
1) In your profile script (.zprofile, .profile, etc), you will set up a symbolic link from a canonical location to the "current" SSH_AUTH_SOCK. Here's how I do it in zsh:
test $SSH_AUTH_SOCK && ln -sf "$SSH_AUTH_SOCK" "/tmp/ssh-agent-$USER-screen"
The "test" is just to prevent an error from displaying if you aren't running ssh-agent (ie you ssh without -A). The second half of that command sets up a symlink in a canonical location that updates itself to the "real" SSH_AUTH_SOCK at login time.
2) In your .screenrc, you just need to override the SSH_AUTH_SOCK to the canonical location:
setenv SSH_AUTH_SOCK "/tmp/ssh-agent-$USER-screen"
Note that you use setenv no matter what shell you use; I think that setenv is screen syntax, not the shell.
And that's it! There are other published solutions out there but they are way more complex and require you to run ssh and screen with aliases and such. I've tried this solution out a bit and it's been 100% rock-solid so far.
Enjoy!
Alan
I've been looking for a solution to this problem for quite some time. Awesome and KISS, thanks!
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHello,
ReplyDeleteI did some modification to you r setup :
replaced
test $SSH_AUTH_SOCK && ln -sf "$SSH_AUTH_SOCK" "/tmp/ssh-agent-$USER-screen"
by:
alias screen="test $SSH_AUTH_SOCK && ln -sf \"$SSH_AUTH_SOCK\" \"/tmp/ssh-agent-$USER-screen\"; screen"
This way I avoid cycle links warning when creating BASH shells in my screen.
I also avoid loosing my agent if I login/logout on the machine with an other shell.
There is still an issue if I have several screens on the same machine...
XL
This comment has been removed by the author.
Delete