Junhc

岂止于博客

JGit

<dependency>
  <groupId>org.eclipse.jgit</groupId>
  <artifactId>org.eclipse.jgit</artifactId>
  <version>5.2.0.201812061821-r</version>
</dependency>
// 打开一个现有仓库
Repository repository = new FileRepositoryBuilder().setGitDir(new File("/usr/local/git/xxx/.git")).build();
Git git = new Git(repository);
git.add().addFilepattern("README.md").call();
git.commit().setMessage("Add new file").call();
// 使用ssh-keygen生成ssh密钥
// 无密码时,直接使用..
git.push().call();
// 有密码时,
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
    @Override
    protected void configure(OpenSshConfig.Host host, Session session) {
        session.setConfig("StrictHostKeyChecking", "no");
    }

   @Override
    protected JSch getJSch(OpenSshConfig.Host hc, FS fs) throws JSchException {
        JSch jSch = super.getJSch(hc, fs);
        jSch.removeAllIdentity();
        jSch.addIdentity(System.getProperty("user.home") + "/.ssh/id_rsa", "123456");
        return jSch;
    }
};
git.push().setTransportConfigCallback(new TransportConfigCallback() {
    @Override
    public void configure(Transport transport) {
        SshTransport sshTransport = (SshTransport) transport;
        sshTransport.setSshSessionFactory(sshSessionFactory);
    }
}).call();
参考资料