我正在尝试通过 ssh 使用 Java 克隆一个 git 项目。我有一个 git-shell 用户的用户名和密码作为凭据。我可以使用以下命令毫无问题地在终端中克隆项目。 (当然是先要密码)
git clone user@HOST:/path/Example.git
但是,当我使用 JGIT api 尝试以下代码时
File localPath = new File("TempProject");
Git.cloneRepository()
.setURI("ssh://HOST/path/example.git")
.setDirectory(localPath)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider("***", "***"))
.call();
我得到了
Exception in thread "main" org.eclipse.jgit.api.errors.TransportException: ssh://HOST/path/example.git: Auth fail
我该怎么办?有任何想法吗? (我使用的是 OSX 10.9.4 和 JDK 1.8)
最佳答案
对于 SSH 身份验证,JGit 使用 JSch . JSch 提供了一个 SshSessionFactory
来创建和处理 SSH 连接。告诉 JGit 应该使用哪个 SSH session 工厂的最快方法是通过 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();
以更明智的方式设置 SshSessionFactory
稍微复杂一些。 CloneCommand
- 与所有可能打开连接的 JGit 命令类一样 - 继承自 TransportCommand
。此类具有 setTransportConfigCallback()
方法,也可用于为实际命令指定 SSH session 工厂。
CloneCommand cloneCommand = Git.cloneRepository();
cloneCommand.setTransportConfigCallback( new TransportConfigCallback() {
@Override
public void configure( Transport transport ) {
if( transport instanceof SshTransport ) {
SshTransport sshTransport = ( SshTransport )transport;
sshTransport.setSshSessionFactory( ... );
}
}
} );
关于java - 通过 Java 使用用户名和密码通过 ssh 克隆 git 存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25951804/