Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone git repository over ssh with username and password by Java

Tags:

java

git

ssh

jgit

I am trying to clone a git project with Java over ssh. I have username and password of a git-shell user as credentials. 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

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)

like image 440
Nuri Tasdemir Avatar asked Sep 20 '14 18:09

Nuri Tasdemir


People also ask

How do I give my Git clone a username and password?

To save username and password in Git, open your “GitHub” remote repository and copy its “URL”. Then, launch “Git Bash”, paste the “URL” with the “$ git clone” command, specify the credential and execute it.


1 Answers

For authentication with SSH, JGit uses JSch. JSch provides an SshSessionFactory to create and dispose SSH connections. The quickest way to tell JGit which SSH session factory should be used is to set it globally through SshSessionFactory.setInstance().

JGit provides an abstract JschConfigSessionFactory, whose configure method can be overridden to provide the password:

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. The CloneCommand - like all JGit command classes that may open a connection - inherits from TransportCommand. This class has a setTransportConfigCallback() method that can also be used to specify the SSH session factory for the actual command.

CloneCommand cloneCommand = Git.cloneRepository();
cloneCommand.setTransportConfigCallback( new TransportConfigCallback() {
  @Override
  public void configure( Transport transport ) {
    if( transport instanceof SshTransport ) {
      SshTransport sshTransport = ( SshTransport )transport;
      sshTransport.setSshSessionFactory( ... );
    }
  }
} );
like image 187
Rüdiger Herrmann Avatar answered Sep 18 '22 16:09

Rüdiger Herrmann