我试图用ssh克隆一个带Java的git项目.我有git-shell用户的用户名和密码作为凭据.我可以使用以下命令在终端中克隆项目,没有任何问题.(当然,它首先要求输入密码)
git clone user@HOST:/path/Example.git
Run Code Online (Sandbox Code Playgroud)
但是当我使用JGIT api尝试以下代码时
File localPath = new File("TempProject");
Git.cloneRepository()
.setURI("ssh://HOST/path/example.git")
.setDirectory(localPath)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider("***", "***"))
.call();
Run Code Online (Sandbox Code Playgroud)
我有
Exception in thread "main" org.eclipse.jgit.api.errors.TransportException: ssh://HOST/path/example.git: Auth fail
Run Code Online (Sandbox Code Playgroud)
我该怎么办?有任何想法吗?(我使用的是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();
Run Code Online (Sandbox Code Playgroud)
以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( ... );
}
}
} );
Run Code Online (Sandbox Code Playgroud)