jgit ssh java,通过ssh使用用户名和密码通过Java克隆git存储库

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)

解决方案

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( ... );

}

}

} );

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值