12

when I make git clone with ssh from a user prompt it works properly.

git clone ssh://URL.com/soft.git soft_git

the ssh key id_rsa and id_rsa.pub are under /home/user/.ssh

my purpose is the execute git with sudo but I got the following error

Cloning into '/home/user/git/soft'...
Permission denied (publickey,keyboard-interactive).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I create a folder /root/.ssh and I copy the ssh keys into it but I got the same error

how to execute git with sudo properly.

3 Answers 3

19

When you run git using sudo, git will run as root. Because git is running as root, ssh is running as root. Because ssh is running as root, it is trying to log on to the remote server as root. The remote server is not okay with this (as it should be!)

You will need to do two things:

  • Put the username in your URL: ssh://[email protected]/soft.git.

  • Make your SSH key available to the root user, because it will look under /root/.ssh instead of /home/user/.ssh. (You could also probably point SSH at the correct key, but I don't know how to do this, and SSH is picky about permissions.)

4

On my computer (Ubunutu 18.04), adding SSH_AUTH_SOCK=$SSH_AUTH_SOCK after sudo and before git fixed the problem:

sudo SSH_AUTH_SOCK=$SSH_AUTH_SOCK git clone [email protected]:my-github-account/my-repo.git 

Normally, sudo's SSH_AUTH_SOCK environment variable won't be set properly. Executing the git clone with SSH_AUTH_SOCK=$SSH_AUTH_SOCK sets sudo's SSH_AUTH_SOCK environment variable to whatever it is for you.

This way, you don't need to add an extra .ssh dir for sudo with copies of your keys, which is what I think one of the other answers suggests.

The solution is more fully explained in this rather old github gist: https://gist.github.com/scottjacobsen/4281310

P.S. I'm adding a new answer several years later; I googled a solution to this problem, and this SO Q/A is one of the first things that comes up.

2

Normally the default remote ssh user is the same as your user name. If you're using sudo this will be root which probably isnt' going to work. You need to supply the remote username.

sudo git clone ssh://[email protected]/soft.git soft_git

You can generally resolve git ssh issues easier by trying to login to the remote with plain ssh. You'll get better diagnostics and can see what's going wrong.

sudo ssh ssh://URL.com/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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