crumbtrail

Oct 15 2009

GNU screen Wrapper for SSH Agent Forwarding

This problem is well-documented around the web, this is just my personal reminder. Others have crafted various solutions varying in complexity. I like this one for the simplicity and easy portability—I don’t remember who to credit for it, unfortunately.

Without getting too deeply into the gory details, if you connect to a remote shell and run GNU screen there, then detach the screen and come back to it in a later SSH session, environment variables that SSH agent forwarding requires to function will have changed and your screen session is none the wiser. This is rather annoying if you frequently connect to a gateway server and use screen to do work on other servers inside of it—your public key will not be forwarded to the internal servers on subsequent connections.

Enter wrapper script to save new SSH variables when you connect again and resume your screen session:

#!/bin/bash
# Wrapper script to set SSH env vars so agent forwarding works when
# resuming screen sessions. Place at ~/bin/screen and make sure
# your personal bin directory has priority in your PATH

for SSHVAR in SSH_CLIENT SSH_TTY SSH_AUTH_SOCK SSH_CONNECTION DISPLAY; do
    echo "export ${SSHVAR}=\"${!SSHVAR}\""
done > ~/.sshvars
/usr/bin/screen $*

Then, a simple alias for your .bashrc, to run once you’ve resumed screen:

# After reconnecting to a screen session, this restores env vars
# to allow agent forwarding to work again
alias fixssh='source ~/.sshvars'

Off you go to now to connect to those internal servers needing your forwarded key.

Page 1 of 1