Java中ssh2密钥连接,JGit SSH密钥 clone/pull/log操作

不多说了,copy的累死我了,真心不好找 -_-

JGit 通过SSH私钥文件clone/pull代码

1.目的及准备工作

# 目的:通过jgit框架通过SSH密钥文件来连接git仓库并clone代码到本地

# 准备工作:

1.需要一个私钥文件,比如C:\Users\xxx\.ssh\id_rsa这个文件,如果是ppk文件(putty生成的用来验证git仓库权限的文件),则找到 puttygen.exe,双击运行后,点击Conversions->import Key(导入ppk文件)->Save private key(保存为一个无后缀名的文件)

2.项目引入Jgit依赖

org.eclipse.jgit

org.eclipse.jgit

3.7.0.201502260915-r

2.通过java代码进行clone

package com.jgittest.util;

import java.io.File;

import org.eclipse.jgit.api.CloneCommand;

import org.eclipse.jgit.api.Git;

import org.eclipse.jgit.lib.Repository;

import org.eclipse.jgit.storage.file.FileRepositoryBuilder;

import org.eclipse.jgit.transport.JschConfigSessionFactory;

import org.eclipse.jgit.transport.OpenSshConfig;

import org.eclipse.jgit.transport.SshSessionFactory;

import org.eclipse.jgit.transport.SshTransport;

import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import org.eclipse.jgit.util.FS;

import com.jcraft.jsch.JSch;

import com.jcraft.jsch.JSchException;

import com.jcraft.jsch.Session;

/**

* git操作工具类

* @author houjiayin.co

*

*/

public class GitUtil {

public static void main(String[] args) {

String localCodeDir = "H:/myGitRepository"; //本地文件夹

String remoteRepoPath = "ssh://***"; //git地址

String keyPath = "H:/private_key" //私钥文件

gitClone(remoteRepoPath, localCodeDir,keyPath);

}

//localRepoPath 为本地文件夹

//keyPath 私钥文件 path

//remoteRepoPath 为 ssh git远端仓库地址

protected static void gitClone(String remoteRepoPath, String localRepoPath,String keyPath) {

//ssh session的工厂,用来创建密匙连接

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 sch = super.createDefaultJSch(fs);

sch.addIdentity(keyPath); //添加私钥文件

return sch;

}

};

//克隆代码库命令

CloneCommand cloneCommand = Git.cloneRepository();

Git git = null;

try {

git = cloneCommand.setURI(remoteRepoPath) //设置远程URI

.setTransportConfigCallback(transport -> {

SshTransport sshTransport = ( SshTransport )transport;

sshTransport.setSshSessionFactory( sshSessionFactory );

})

.setDirectory(new File(localRepoPath)) //设置下载存放路径

.call();

System.out.println("success");

} catch (Exception e) {

System.out.println("fail");

e.printStackTrace();

} finally {

if (git != null) {

git.close();

}

}

}

3. pull代码

//localRepoPath 为 .git 的 path 如 : D:\\gitRepository\\.git

//keyPath 私钥文件 path

public static void pullCode(String remoteRepoPath, String localRepoPath, String keyPath) {

System.out.println("===" + remoteRepoPath + "===" + localRepoPath + "===" + keyPath);

//ssh session的工厂,用来创建密匙连接

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 sch = super.createDefaultJSch(fs);

sch.addIdentity(keyPath);

return sch;

}

};

try {

//关联到本地仓库

FileRepository fileRepository = new FileRepository(new File(localRepoPath));

Git pullGit = new Git(fileRepository);

//设置密钥,拉取文件

PullCommand pullCommand = pullGit

.pull()

.setTransportConfigCallback(

transport -> {

SshTransport sshTransport = ( SshTransport )transport;

sshTransport.setSshSessionFactory( sshSessionFactory );

});

pullCommand.call();

}catch (Exception e) {

e.printStackTrace();

}

}

JGit 获取提交信息/详细提交日志

1.提交信息

//此方法获取了仓库内(path下,有可能为仓库下子文件夹)的所有提交版本号

public static List getGitVersions(String path) {

List versions = new ArrayList<>();

try {

Git git = Git.open(new File(path));

Repository repository = git.getRepository();

Git git1 = new Git(repository);

Iterable commits = git.log().all().call();

int count = 0;

for (RevCommit commit : commits) {

System.out.println("LogCommit: " + commit);

System.out.println("===" + commit.getFullMessage());

String version = commit.getName(); //版本号,用来查询详细信息

versions.add(version);

System.out.println("===" + commit.getName());

System.out.println("===" + commit.getAuthorIdent());

count++;

}

return versions;

}catch (Exception e) {

e.printStackTrace();

}

return null;

}

2. 获取提交的详细信息

/**

* 获取两个版本间提交详细记录

* @param path

*/

//version 为 上一个方法查询出来的版本号

public static void showDiff(String path,String oldVersion,String newVersion) {

try {

Git git = Git.open(new File(path));

Repository repository = git.getRepository();

//旧版本

AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, oldVersion);

//新版本

AbstractTreeIterator newTreeParser = prepareTreeParser(repository, newVersion);

List diff = git.diff().

setOldTree(oldTreeParser).

setNewTree(newTreeParser).

call();

for (DiffEntry entry : diff) {

System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());

//此处可传一个输出流获取提交详情

DiffFormatter formatter = new DiffFormatter(System.out);

formatter.setRepository(repository);

formatter.format(entry);

}

}catch (Exception e) {

e.printStackTrace();

}

}

附几个有用的 jgit 资料地址

# git官网对jgit的介绍

https://git-scm.com/book/zh/v2/%E9%99%84%E5%BD%95-B%3A-%E5%9C%A8%E4%BD%A0%E7%9A%84%E5%BA%94%E7%94%A8%E4%B8%AD%E5%B5%8C%E5%85%A5-Git-JGit

# jgit超有用的各种demo地址

https://github.com/centic9/jgit-cookbook

# 一些常用的jgit方法

https://my.oschina.net/u/4339481/blog/4748737

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用jgit通过SSH协议访问Git仓库,需要完成以下几个步骤: 1. 配置SSH密钥 首先,您需要在本地生成一对SSH密钥,并将公钥添加到Git仓库。这样,在使用jgit时,就可以通过私钥进行身份验证,从而获得对Git仓库的访问权限。具体的配置方法可以参考Git官方文档:[Generating a new SSH key and adding it to the ssh-agent](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent)。 2. 使用SSH协议URL访问Git仓库 在Java代码,您可以使用SSH协议URL访问Git仓库。例如,如果您要访问的Git仓库URL为`git@github.com:user/repo.git`,则可以使用以下代码: ```java String repoUrl = "git@github.com:user/repo.git"; Git git = Git.cloneRepository() .setURI(repoUrl) .setTransportConfigCallback(new TransportConfigCallback() { public void configure(Transport transport) { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(new JschConfigSessionFactory() { public void configure(Host hc, Session session) { // 配置SSH会话,例如添加私钥 } }); } }) .call(); ``` 在上述代码,`setURI()`方法设置Git仓库URL,`setTransportConfigCallback()`方法配置SSH会话,`call()`方法开始进行Git操作。在`configure()`方法,您可以配置SSH会话,例如添加私钥、设置端口号等。 3. 完成Git操作 通过以上步骤,您就可以使用jgit通过SSH协议访问Git仓库,并进行相应的Git操作了。在Git操作完成后,您需要关闭Git对象,释放资源,例如: ```java git.close(); ``` 希望以上内容能够帮助您完成jgit通过SSH协议访问Git仓库的操作。如果您有任何问题或疑问,请随时在此继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值