clone a git repository with SSH and libgit2sharp

2019-07-06 15:10发布

I'm trying to use the library "libgit2sharp" to clone a repository via a SSH key and... I can't find anything... I can clone it via "https" but what I'd like to do is using an SSH key. It's really unclear if it is supported or not.

1条回答
趁早两清
2楼-- · 2019-07-06 15:38

As of now, there is a SSH implementation using libssh2 library. You can find it here LibGit2Sharp - SSH

You should add libgit2sharp-ssh dependency on you Project to be able to use it. It is available as a nugget: https://www.nuget.org/packages/LibGit2Sharp-SSH

Disclaimer: I haven't found a formal usage guide yet, what I know is from putting together bits and pieces from other user questions through LibGit2 forums.

From what I understood, you would need to create a new credential using eitherSshUserKeyCredentials OR SshAgentCredentials to authenticate using SSH, and pass it as part of CloneOptions.

In the sample code I use "git" as user, simply because the remote would be something like git@bitbucket.org:project/reponame.git , in which case "git" is the correct user, otherwise you will get an error saying

$exception  {"username does not match previous request"}LibGit2Sharp.LibGit2SharpException

The code to clone a repo with SSH should be something like that:

public CloneOptions cloningSSHAuthentication(string username, string path_to_public_key_file, string path_to_private_key_file)
    {
        CloneOptions options = new CloneOptions();
        SshUserKeyCredentials credentials = new SshUserKeyCredentials();
        credentials.Username = username;
        credentials.PublicKey = path_to_public_key_file;
        credentials.PrivateKey =  path_to_private_key_file;
        credentials.Passphrase = "ssh_key_password";
        options.CredentialsProvider = new LibGit2Sharp.Handlers.CredentialsHandler((url, usernameFromUrl, types) =>  credentials) ;
        return options;
    }

public CloneOptions cloneSSHAgent(string username){
        CloneOptions options = new CloneOptions();
        SshAgentCredentials credentials = new SshAgentCredentials();
        credentials.Username = username;
        var handler = new LibGit2Sharp.Handlers.CredentialsHandler((url, usernameFromUrl, types) => credentials);
        options.CredentialsProvider = handler;
        return options;

}

public void CloneRepo(string remotePath, string localPath){
    CloneOptions options = cloningSSHAuthentication("git", "C:\\folder\\id_rsa.pub", "C:\\folder\\id_rsa");
    Repository.Clone(remotePath, localPath, options);
}
查看更多
登录 后发表回答