make git clone with sudo

18,248

Solution 1

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.)

Solution 2

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.

Share:
18,248
Anis_Stack
Author by

Anis_Stack

Updated on July 24, 2022

Comments

  • Anis_Stack
    Anis_Stack almost 2 years

    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.