簡體   English   中英

使用Java用戶名和密碼在ssh上克隆git存儲庫

[英]Clone git repository over ssh with username and password by Java

我試圖用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會話工廠的最快方法是通過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會話工廠。

CloneCommand cloneCommand = Git.cloneRepository();
cloneCommand.setTransportConfigCallback( new TransportConfigCallback() {
  @Override
  public void configure( Transport transport ) {
    if( transport instanceof SshTransport ) {
      SshTransport sshTransport = ( SshTransport )transport;
      sshTransport.setSshSessionFactory( ... );
    }
  }
} );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM