I want to be able to connect to a server, start a sudo shell, then use agent forwarding to connect to another server (in order to use SCP to copy files to a protected area). But:

ubuntu@tunnelator:/var/www$ ssh -p 10022 stevebennett@localhost
Last login: Fri Apr  5 10:54:03 2013 from localhost
~ exit
Connection to localhost closed.

ubuntu@tunnelator:/var/www$ sudo ssh -p 10022 stevebennett@localhost

Presumably, starting the sudo shell is killing the agent forwarding. The difference is this:

debug1: Offering RSA public key: id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: Authentication succeeded (publickey).


debug1: Next authentication method: publickey
debug1: Trying private key: /root/.ssh/id_rsa
debug1: Trying private key: /root/.ssh/id_dsa
debug1: Trying private key: /root/.ssh/id_ecdsa
debug1: Next authentication method: keyboard-interactive

Is there a way to make this work? (The setup is roughly as described here: http://codysoyland.com/2010/jun/6/ssh-tip-automatic-reverse-tunnels-workflow-simplif/)


Thanks to user157963's suggestion, this turns out to be easy:

sudo -E ssh -p 10022 stevebennett@localhost

Or, to be a bit more selective, you can do this:

sudo su -l -c "export SSH_AUTH_SOCK=$SSH_AUTH_SOCK; ssh -p 10022 stevebennett@localhost"

(Note this only works when su'ing to the root user - it needs to be able to read the original socket file.)

I had mistakenly thought that the $SSH_AUTH_SOCK environment variable was already being preserved. Tip: the following command doesn't tell you anything useful :)

sudo echo $SSH_AUTH_SOCK

Whereas this does:

sudo bash -c 'echo $SSH_AUTH_SOCK'
  • Additionally you can just sudo -sE if you want to have a shell as root. -E preserves the current environment which includes $SSH_AUTH_SOCK which houses the forwarding agent information – Steve Tauber Jan 15 '16 at 20:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.