简体   繁体   English

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

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

I am trying to clone a git project with Java over ssh. 我试图用ssh克隆一个带Java的git项目。 I have username and password of a git-shell user as credentials. 我有git-shell用户的用户名和密码作为凭据。 I can clone the project in terminal using the following command with no problem. 我可以使用以下命令在终端中克隆项目,没有任何问题。 (Of course, it asks for the password first) (当然,它首先要求输入密码)

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

However when I try the following code using JGIT api 但是当我使用JGIT api尝试以下代码时

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

I got 我有

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

What should I do? 我该怎么办? Any ideas? 有任何想法吗? (I am using OSX 10.9.4 and JDK 1.8) (我使用的是OSX 10.9.4和JDK 1.8)

For authentication with SSH, JGit uses JSch . 对于使用SSH进行身份验证,JGit使用JSch JSch provides an SshSessionFactory to create and dispose SSH connections. JSch提供了一个SshSessionFactory来创建和配置SSH连接。 The quickest way to tell JGit which SSH session factory should be used is to set it globally through SshSessionFactory.setInstance() . 告诉JGit应该使用哪个SSH会话工厂的最快方法是通过SshSessionFactory.setInstance()全局设置它。

JGit provides an abstract JschConfigSessionFactory , whose configure method can be overridden to provide the password: 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();

To set the SshSessionFactory in a more sensible way is slightly more complex. 以更合理的方式设置SshSessionFactory稍微复杂一些。 The CloneCommand - like all JGit command classes that may open a connection - inherits from TransportCommand . CloneCommand - 与可能打开连接的所有JGit命令类一样 - 继承自TransportCommand This class has a setTransportConfigCallback() method that can also be used to specify the SSH session factory for the actual command. 此类具有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