clone a git repository with SSH and libgit2sharp

偶尔善良 提交于 2019-12-23 12:24:08

问题


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:


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);
}


来源:https://stackoverflow.com/questions/40700154/clone-a-git-repository-with-ssh-and-libgit2sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!