Clone git repository over ssh with username and password by Java

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");
    .setCredentialsProvider(new UsernamePasswordCredentialsProvider("***", "***"))

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)

  • Github: Permission denied (publickey) but I got “You've successfully authenticated” message
  • What are the drawbacks to hosting a git repository with WebDAV instead of SSH?
  • Issue in Bot integration with bitbucket
  • How do i set a private ssh key for hudson / jenkins to access bitbucket?
  • How to switch from first github account to second?
  • Not able to connect to github repo via ssh using http proxy tunnel
  • Does heroku use my ssh key to fetch builpacks?
  • Authentication error when setting up Jenkins to talk to git
  • One Solution collect form web for “Clone git repository over ssh with username and password by Java”

    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() {
        protected void configure( Host host, Session session ) {
          session.setPassword( "password" );
    } );
      .setURI( "ssh://username@host/path/repo.git" )
      .setDirectory( "/path/to/local/repo" )

    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() {
      public void configure( Transport transport ) {
        if( transport instanceof SshTransport ) {
          SshTransport sshTransport = ( SshTransport )transport;
          sshTransport.setSshSessionFactory( ... );
    } );
    Git Baby is a git and github fan, let's start git clone.