[java]jGit指定sshkey

659 阅读1分钟

代码示例:

SshSessionFactory sshSessionFactory = new JschConfigSessionFactory(){
    @Override
    protected void configure(OpenSshConfig.Host host, Session session ) {
        session.setConfig("StrictHostKeyChecking", "no");
    }
    @Override
    protected JSch createDefaultJSch(FS fs ) throws JSchException {
        JSch defaultJSch = super.createDefaultJSch( fs );
        defaultJSch.addIdentity( sshKeyFile.getAbsolutePath());
        return defaultJSch;
    }
};
CloneCommand cloneCommand = Git.cloneRepository();
cloneCommand.setURI( gitUrl);
cloneCommand.setTransportConfigCallback( new TransportConfigCallback() {
    @Override
    public void configure( Transport transport ) {
        SshTransport sshTransport = ( SshTransport )transport;
        sshTransport.setSshSessionFactory( sshSessionFactory );
    }
} );

cloneCommand.setDirectory(codeDir);
cloneCommand.call();

代码说明:
这里重写了一个方法来手动指定sshKey文件的路径,否则默认会去找/.ssh/id_rsa

另外,如果出现报错信息:Algorithm negotiation fail,则需要升级jsch版本至0.1.54或以上。

参考资源:www.eclipse.org/forums/inde…