我使用JGit来访问远程Git仓库,我需要使用SSH。 JGit使用JSch来提供安全访问。但是,我不确定如何为JGit设置密钥文件和知道主机文件。我试过的如下。与JGit一起使用密钥来安全访问Git存储库
创建的SshSessionFactory的定制配置,使用由子类JSchConfigSessionFactory:
public class CustomJschConfigSessionFactory extends JschConfigSessionFactory {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
session.setConfig("StrictHostKeyChecking", "yes");
}
}
在我访问远程GIT中回购类,做了以下内容:
CustomJschConfigSessionFactory jschConfigSessionFactory = new CustomJschConfigSessionFactory();
JSch jsch = new JSch();
try {
jsch.addIdentity(".ssh/id_rsa");
jsch.setKnownHosts(".ssh/known_hosts");
} catch (JSchException e) {
e.printStackTrace();
}
SshSessionFactory.setInstance(jschConfigSessionFactory);
我不能了解如何将此JSch对象与JGit关联,以便它可以成功连接到远程存储库。当我试着使用JGit克隆它,我得到以下异常:
org.eclipse.jgit.api.errors.TransportException: [email protected]:abc.org/test_repo.git: reject HostKey: git.test.com
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:137)
at org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:178)
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:125)
at GitTest.cloneRepo(GitTest.java:109)
at GitTest.main(GitTest.java:223)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.eclipse.jgit.errors.TransportException: [email protected]:abc.org/test_repo.git: reject HostKey: git.test.com
at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:142)
at org.eclipse.jgit.transport.SshTransport.getSession(SshTransport.java:121)
at org.eclipse.jgit.transport.TransportGitSsh$SshFetchConnection.<init>(TransportGitSsh.java:248)
at org.eclipse.jgit.transport.TransportGitSsh.openFetch(TransportGitSsh.java:147)
at org.eclipse.jgit.transport.FetchProcess.executeImp(FetchProcess.java:136)
at org.eclipse.jgit.transport.FetchProcess.execute(FetchProcess.java:122)
at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1104)
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:128)
... 9 more
Caused by: com.jcraft.jsch.JSchException: reject HostKey: git.test.com
at com.jcraft.jsch.Session.checkHost(Session.java:748)
at com.jcraft.jsch.Session.connect(Session.java:321)
at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:116)
... 16 more
我已经加入了git.test.com进入到我的/etc/hosts
文件。我使用相同的代码来访问一个http url的git repo,所以它的代码工作正常。这是失败的关键处理部分。任何想法如何处理这个?
我的问题是,我需要能够指定密码私钥,您可以添加另一个参数'addIdentity'或通过创建自己的实现'UserInfo'的类,然后将'Session'参数设置为'CustomConfigSessionFactory'的'configure'方法以使用'UserInfo'。 – WhiteKnight
特别感谢'jsch.removeAllIdentity()'提示! – Vincent