下面列出了怎么用org.eclipse.jgit.transport.SshTransport的API类实例代码及写法,或者点击链接到github查看源代码。
private void fetch(String branchName) throws GitAPIException {
logger.info("Fetching branch " + branchName);
if (!branchName.startsWith(REFS_REMOTES)) {
throw new IllegalArgumentException("Branch name '" + branchName + "' is not tracking branch name since it does not start " + REFS_REMOTES);
}
String remoteName = extractRemoteName(branchName);
String shortName = extractShortName(remoteName, branchName);
FetchCommand fetchCommand = git.fetch()
.setCredentialsProvider(credentialsProvider)
.setRemote(remoteName)
.setRefSpecs(new RefSpec(REFS_HEADS + shortName + ":" + branchName));
if (configuration.useJschAgentProxy) {
fetchCommand.setTransportConfigCallback(transport -> {
if (transport instanceof SshTransport) {
((SshTransport) transport).setSshSessionFactory(new AgentProxyAwareJschConfigSessionFactory());
}
});
}
fetchCommand.call();
}
private <T extends TransportCommand> void configureBasicAuthentication(
ClusterMember remoteNode, T gitCommand, TextEncryptor encryptor, boolean sshProtocol) throws CryptoException {
String password = encryptor.decrypt(remoteNode.getGitPassword());
UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
remoteNode.getGitUsername(), password);
if (sshProtocol) {
gitCommand.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(new StrictHostCheckingOffSshSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
super.configure(host, session);
session.setPassword(password);
}
});
});
}
gitCommand.setCredentialsProvider(credentialsProvider);
}
private <T extends TransportCommand> void configurePrivateKeyAuthentication(
ClusterMember remoteNode, T gitCommand, TextEncryptor encryptor, final Path tempKey)
throws CryptoException, IOException {
String privateKey = encryptor.decrypt(remoteNode.getGitPrivateKey());
try {
Files.write(tempKey, privateKey.getBytes());
} catch (IOException e) {
throw new IOException("Failed to write private key for SSH connection to temp location", e);
}
tempKey.toFile().deleteOnExit();
gitCommand.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport)transport;
sshTransport.setSshSessionFactory(new StrictHostCheckingOffSshSessionFactory() {
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
JSch defaultJSch = super.createDefaultJSch(fs);
defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
return defaultJSch;
}
});
});
}
public static void main(String[] args) throws GitAPIException {
Git.cloneRepository()
.setURI("[email protected]:jiangzeyin/test.git")
.setDirectory(new File("D:\\test\\gitssh"))
.setTransportConfigCallback(new TransportConfigCallback() {
@Override
public void configure(Transport transport) {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host hc, Session session) {
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("");
}
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
JSch defaultJSch = super.createDefaultJSch(fs);
defaultJSch.addIdentity("C:\\Users\\Colorful\\.ssh\\id_rsa.pub");
return defaultJSch;
}
});
}
})
.call();
}
@Override
public void setup(TransportCommand<?, ?> command) throws Exception {
this.sessionFactory = new PrivateKeySessionFactory(privateKey);
command.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sessionFactory);
});
}
private TransportConfigCallback buildTransportConfigCallback() {
if (this.providerSessionFactoryEither instanceof Either.Left) return null;
SshSessionFactory sshSessionFactory = ((Either.Right<CredentialsProvider, SshSessionFactory>) this.providerSessionFactoryEither).getRight();
return transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sshSessionFactory);
};
}
@Override
public void configure(Transport transport) {
if (transport instanceof SshTransport) {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(new PropertyBasedSshSessionFactory(
new SshUriPropertyProcessor(this.sshUriProperties)
.getSshKeysByHostname(),
new JSch()));
}
}
@SuppressWarnings("SameParameterValue")
private Transport mockSshTransport(String uri) throws URISyntaxException {
Transport transport = Mockito.mock(SshTransport.class);
when(transport.getURI()).thenReturn(new URIish(uri));
return transport;
}
private boolean isRemoteValid(Git git, String remote, String authenticationType,
String remoteUsername, String remotePassword, String remoteToken,
String remotePrivateKey)
throws CryptoException, IOException, ServiceLayerException, GitAPIException {
LsRemoteCommand lsRemoteCommand = git.lsRemote();
lsRemoteCommand.setRemote(remote);
switch (authenticationType) {
case NONE:
logger.debug("No authentication");
break;
case BASIC:
logger.debug("Basic authentication");
lsRemoteCommand.setCredentialsProvider(
new UsernamePasswordCredentialsProvider(remoteUsername, remotePassword));
break;
case TOKEN:
logger.debug("Token based authentication");
lsRemoteCommand.setCredentialsProvider(
new UsernamePasswordCredentialsProvider(remoteToken, EMPTY));
break;
case PRIVATE_KEY:
logger.debug("Private key authentication");
final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
tempKey.toFile().deleteOnExit();
lsRemoteCommand.setTransportConfigCallback(
new TransportConfigCallback() {
@Override
public void configure(Transport transport) {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(getSshSessionFactory(remotePrivateKey, tempKey));
}
});
Files.delete(tempKey);
break;
default:
throw new ServiceLayerException("Unsupported authentication type " + authenticationType);
}
lsRemoteCommand.call();
return true;
}
private <T extends TransportCommand> void configureTokenAuthentication(
ClusterMember remoteNode, T gitCommand, TextEncryptor encryptor, boolean sshProtocol) throws CryptoException {
UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
encryptor.decrypt(remoteNode.getGitToken()), StringUtils.EMPTY);
if (sshProtocol) {
gitCommand.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(new StrictHostCheckingOffSshSessionFactory());
});
}
gitCommand.setCredentialsProvider(credentialsProvider);
}
@Override
public void configure(Transport transport) {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(SshdSessionFactory.getInstance());
}
public <T extends TransportCommand> T setAuthenticationForCommand(T gitCommand, String authenticationType,
String username, String password, String token,
String privateKey, Path tempKey, boolean decrypt)
throws CryptoException, ServiceLayerException {
String passwordValue = password;
String tokenValue = token;
String privateKeyValue = privateKey;
if (decrypt) {
if (!StringUtils.isEmpty(password)) {
passwordValue = encryptor.decrypt(password);
}
if (!StringUtils.isEmpty(token)) {
tokenValue = encryptor.decrypt(token);
}
if (!StringUtils.isEmpty(privateKey)) {
privateKeyValue = encryptor.decrypt(privateKey);
}
}
final String pk = privateKeyValue;
switch (authenticationType) {
case RemoteRepository.AuthenticationType.NONE:
logger.debug("No authentication");
break;
case RemoteRepository.AuthenticationType.BASIC:
logger.debug("Basic authentication");
UsernamePasswordCredentialsProvider credentialsProviderUP =
new UsernamePasswordCredentialsProvider(username, passwordValue);
gitCommand.setCredentialsProvider(credentialsProviderUP);
break;
case RemoteRepository.AuthenticationType.TOKEN:
logger.debug("Token based authentication");
UsernamePasswordCredentialsProvider credentialsProvider =
new UsernamePasswordCredentialsProvider(tokenValue, StringUtils.EMPTY);
gitCommand.setCredentialsProvider(credentialsProvider);
break;
case RemoteRepository.AuthenticationType.PRIVATE_KEY:
logger.debug("Private key authentication");
tempKey.toFile().deleteOnExit();
gitCommand.setTransportConfigCallback(new TransportConfigCallback() {
@Override
public void configure(Transport transport) {
SshTransport sshTransport = (SshTransport)transport;
sshTransport.setSshSessionFactory(getSshSessionFactory(pk, tempKey));
}
});
break;
default:
throw new ServiceLayerException("Unsupported authentication type " + authenticationType);
}
return gitCommand;
}