繁体   English   中英

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

[英]Clone git repository over ssh with username and password by Java

我试图用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进行身份验证,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命令类一样 - 继承自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( ... );
    }
  }
} );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM