到目前为止,有一个使用 libssh2 库的 SSH 实现。你可以在这里找到它LibGit2Sharp - SSH
您应该在您的项目上添加 libgit2sharp-ssh 依赖项才能使用它。它以金块的形式提供:https://www.nuget.org/packages/LibGit2Sharp-SSH
免责声明:我还没有找到正式的使用指南,我所知道的是通过 LibGit2 论坛将其他用户问题的点点滴滴整理出来。
据我了解,您需要使用SshUserKeyCredentials 或SshAgentCredentials 创建一个新凭据以使用SSH 进行身份验证,并将其作为CloneOptions 的一部分传递。
在示例代码中,我使用“git”作为用户,只是因为远程类似于 git@bitbucket.org:project/reponame.git ,在哪种情况“git”是正确的用户,否则你会得到一个错误提示
$exception {"username does not match previous request"}LibGit2Sharp.LibGit2SharpException
使用 SSH 克隆 repo 的代码应该是这样的:
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);
}