NGIT/JGIT/Git# SSH会话与私钥克隆Git存储库



会话部分使用私钥连接,没有问题。然而,当我做一个git克隆,它给出了错误'Auth Fail'。我如何包装,绑定或使连接的会话工作与git克隆。我在。net 4.0下使用NGIT,但不认为这有什么关系,因为JGIT几乎是一样的。

有什么想法吗?

谢谢加文

        JSch jsch = new JSch();
        Session session = jsch.GetSession(gUser, gHost, 22);
        jsch.AddIdentity(PrivateKeyFile); // If I leave this line out, the session fails to Auth. therefore it works.
        Hashtable table = new Hashtable();
        table["StrictHostKeyChecking"] = "no"; // this works
        session.SetConfig(table);
        session.Connect(); // the session connects.

        URIish u = new URIish();
        u.SetPort(22);
        u.SetHost(gHost);
        u.SetUser(gUser);            
        NGit.Transport.JschSession jschSession = new JschSession(session,u );
        if (session.IsConnected())
        {
            try
            {
                CloneCommand clone = Git.CloneRepository()
                    .SetURI(gitAddress)
                    .SetDirectory(folderToSave);                                        
                clone.Call();                  
             //   MessageBox.Show(Status, gitAddress, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                // AUth Fail..... ????
            }
        }
        else
        {
            session.Disconnect();
        }
        session.Disconnect();

这里的问题是会话对象实际上在任何时候都没有与克隆命令相关联。因此,您为设置会话所做的所有工作实际上没有做任何事情,因为CloneCommand将自己创建自己的会话(使用默认会话项)。

克隆命令将从SSHSessionFactory获取它实际使用的会话。首先,需要创建一个实现SSHSessionFactory抽象类的类,就像我在下面所做的那样:

public class MySSHSessionFactory : SshSessionFactory
{
    private readonly JSch j;
    public MySSHSessionFactory()
    {
        this.j = new JSch();
    }
    public void Initialize()
    {
        this.j.SetKnownHosts(@"C:/known_hosts");
        this.j.AddIdentity(@"C:id_rsa");
    }
    public override RemoteSession GetSession(URIish uri, CredentialsProvider credentialsProvider, NGit.Util.FS fs, int tms)
    {
        var session = this.j.GetSession(uri.GetUser(), uri.GetHost());
        session.SetUserInfo(new MyUserInfo());
        session.Connect();
        return new JschSession(session, uri);
    }
}

然后你可以设置所有新的Git命令在需要使用会话时使用这个工厂:

var sessionFactory = new MySSHSessionFactory();
sessionFactory.Initialize();
SshSessionFactory.SetInstance(sessionFactory);
// Now you can do a clone command.

请注意,我仍然在弄清楚这个库,所以我可能没有以最佳方式编写MySSHSessionFactory(例如,它是否处理会话关闭的容错?)。但这至少是个开始。

最新更新