使用Java用户名和密码在ssh上克隆git存储库

我试图用ssh克隆一个带Java的git项目。 我有git-shell用户的用户名和密码作为凭据。 我可以使用以下命令在终端中克隆项目,没有问题。 (当然,它首先要求输入密码)

git clone user@HOST:/path/Example.git 

但是当我使用JGIT api尝试以下代码时

 File localPath = new File("TempProject"); Git.cloneRepository() .setURI("ssh://HOST/path/example.git") .setDirectory(localPath) .setCredentialsProvider(new UsernamePasswordCredentialsProvider("***", "***")) .call(); 

我有

 Exception in thread "main" org.eclipse.jgit.api.errors.TransportException: ssh://HOST/path/example.git: Auth fail 

我该怎么办? 有任何想法吗? (我使用的是OSX 10.9.4和JDK 1.8)

对于使用SSH进行身份validation,JGit使用JSch 。 JSch提供了一个SshSessionFactory来创建和配置SSH连接。 告诉JGit应该使用哪个SSH会话工厂的最快方法是通过SshSessionFactory.setInstance()全局设置它。

JGit提供了一个抽象的JschConfigSessionFactory ,可以重写其configure方法以提供密码:

 SshSessionFactory.setInstance( new JschConfigSessionFactory() { @Override protected void configure( Host host, Session session ) { session.setPassword( "password" ); } } ); Git.cloneRepository() .setURI( "ssh://username@host/path/repo.git" ) .setDirectory( "/path/to/local/repo" ) .call(); 

以更合理的方式设置SshSessionFactory稍微复杂一些。 CloneCommand – 与可能打开连接的所有JGit命令类一样 – inheritance自TransportCommand 。 此类具有setTransportConfigCallback()方法,该方法还可用于指定实际命令的SSH会话工厂。

 CloneCommand cloneCommand = Git.cloneRepository(); cloneCommand.setTransportConfigCallback( new TransportConfigCallback() { @Override public void configure( Transport transport ) { if( transport instanceof SshTransport ) { SshTransport sshTransport = ( SshTransport )transport; sshTransport.setSshSessionFactory( ... ); } } } );