How can I run SSH as a different user on the same Ubuntu installation?

Solution 1:

Alternative 1 - Configuring sudo

Sudo is configure in the sudoers file which you should only edit through the visudo command.

This configuration file can override certain environment variables with the option env_reset. How to proceed:

visudo

Then find a line that states:

Defaults env_reset 

and add after it (e.g. example with the HOME environement):

Defaults env_keep = "HOME"

This example is for every sudo configuration you may have. You can also specify it on a per user/group basis. See sudoers manual page.

Alternative 2 - configuring SSH

You can use the configuration file of SSH to specify users, key to use, etc. I have explain that at SuperUser.

Proposed solution (but you will have to correct the missing and assumed bits), edit the file /root/.ssh/config and set its permission chmod 0600 /root/.ssh/config:

Host host.com
  User dan
  IdentityFile /home/dan/.ssh/id_rsa

Then as root, you can do the next command and it will use the proper SSH identifications:

git clone host.com:git-repo $PATH_TO_INSTALLATION

Solution 2:

Since the script is running as root, it can su straight to the unpriviliged user. Roots don't need to sudo, sudo is for lusers ;-).

Assuming the unprivileged user is dan, and $PATH_TO_INSTALLATION is set in the surrounding script:

su -lc "git clone [email protected]:git-repo $PATH_TO_INSTALLATION" dan

Note that $PATH_TO_INSTALLATION must be writable by dan.