我正在尝试使用jgit的api和以下代码进行git pull/push
org.eclipse.jgit.api.Git.open(theRepoFile).pull().call()
但我有异常(exception)
JSchException Auth fail
com.jcraft.jsch.Session.connect (Session.java:461)
org.eclipse.jgit.transport.JschConfigSessionFactory.getSession (JschConfigSessionFactory.java:116)
org.eclipse.jgit.transport.SshTransport.getSession (SshTransport.java:121)
org.eclipse.jgit.transport.TransportGitSsh$SshPushConnection.<init> (TransportGitSsh.java:306)
org.eclipse.jgit.transport.TransportGitSsh.openPush (TransportGitSsh.java:152)
org.eclipse.jgit.transport.PushProcess.execute (PushProcess.java:130)
org.eclipse.jgit.transport.Transport.push (Transport.java:1127)
org.eclipse.jgit.api.PushCommand.call (PushCommand.java:153)
即使使用cgit pull和push也可以。
我尝试检查示例代码
Java git client using jgit
但以上问题并未提供完整的编码示例,说明了使用远程 repo 进行git pull所需的条件,该 repo 通常通过ssh key 进行身份验证。应该有一种方法可以从
~/.ssh/
或Windows等效项中获取证书信息。 最佳答案
Jsch将自动检测您的SSH key ,但是如果这些 key 受密码保护,则会失败。您需要通过CredentialsProvider指定密码,如下所示:
JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host hc, Session session) {
CredentialsProvider provider = new CredentialsProvider() {
@Override
public boolean isInteractive() {
return false;
}
@Override
public boolean supports(CredentialItem... items) {
return true;
}
@Override
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
for (CredentialItem item : items) {
((CredentialItem.StringType) item).setValue("yourpassphrase");
}
return true;
}
};
UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
session.setUserInfo(userInfo);
}
};
SshSessionFactory.setInstance(sessionFactory);